[18389] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 557 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Mar 23 21:06:00 2001

Date: Fri, 23 Mar 2001 18:05:14 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <985399513-v10-i557@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Fri, 23 Mar 2001     Volume: 10 Number: 557

Today's topics:
    Re: Can perl handle 'fields' like awk can? (e)
    Re: Creating array context <iltzu@sci.invalid>
    Re: every 15 seconds (Gwyn Judd)
    Re: every 15 seconds (Chris Fedde)
    Re: every 15 seconds (Logan Shaw)
        eXtropia - good tools? <info@HunterShooter.com>
    Re: Hmmm... Which PERL Book Is Best Suited For This??? (---Pete---)
    Re: Hmmm... Which PERL Book Is Best Suited For This??? (---Pete---)
    Re: Hmmm... Which PERL Book Is Best Suited For This??? (---Pete---)
    Re: How can I read a file backwards? (Monte)
    Re: How can I read a file backwards? <callgirl@la.znet.com>
    Re: Problem with sockets and name based virtual host (David Efflandt)
        Question: Addressing Strings? <zhester@enetis.net>
    Re: Question: Addressing Strings? <elijah@workspot.net>
    Re: Question: Addressing Strings? (Logan Shaw)
        regexp exception confusion <jhall@ifxonline.com>
    Re: Statistics (Martien Verbruggen)
    Re: Statistics (Abigail)
    Re: Threaded Perl on FreeBSD <dan@tuatha.sidhe.org>
    Re: use CGI error <zhester@enetis.net>
    Re: use CGI error (David Efflandt)
    Re: use CGI error (Logan Shaw)
    Re: use CGI error (Cosmic Cruizer)
    Re: using closures (road to OO) <uri@sysarch.com>
    Re: Wild Card Search!! (Logan Shaw)
        Digest Administrivia (Last modified: 16 Sep 99) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: 24 Mar 2001 01:49:06 GMT
From: sendthis@delthis.yahoo.com (e)
Subject: Re: Can perl handle 'fields' like awk can?
Message-Id: <E0EB091411667116.D1482DCE930554C0.454737F679245DED@lp.airnews.net>

Thanks I'll give that a try.

e

In article <GAo3CD.GJn@presby.edu>, jtbell@presby.edu says...
>
>In article 
<5C206010769BFDA9.43FAEBB4EBD580C0.686ED4A62B0EAB6C@lp.airnews.net>,
>e <sendthis@yahoo.delthisandasdf.com> wrote:
>>
>>This is what I'm trying to do... (not exactly.)
>>
>>#!/bin/perl
>>
>>open (FILE,"results.xls");
>>@array = <FILE>;
>>close (FILE);
>>
>>foreach $line (@array)
>>{
>>
>>print $line; # this works and prints contents of line
>>print $line [6]; # this returns no value
>
>Indeed, it shouldn't.  $line is not an array, it's a scalar that contains 
>a string.  You need to "split" the string into its component fields, 
>according to whatever separator you're using.  Assuming you're using '\t' 
>(tab) as the separator, you can construct an array of all the fields 
>(minus the separators) as follows:
>
>   @fields = split (/\t/, $Line);
>
>Then $fields[6] will give you the seventh field.  If you don't need the 
>other fields, just the seventh one:
>
>   $whatever = (split (/\t/, $Line))[6];
>
>You can also extract multiple fields this way:
>
>   ($firstname, $lastname, $whatever) = (split (/\t/, $Line))[0,1,6];
>
>-- 
>Jon Bell <jtbell@presby.edu>                        Presbyterian College
>Dept. of Physics and Computer Science        Clinton, South Carolina USA



------------------------------

Date: 23 Mar 2001 23:27:14 GMT
From: Ilmari Karonen <iltzu@sci.invalid>
Subject: Re: Creating array context
Message-Id: <985389488.14519@itz.pp.sci.fi>

In article <es5mbt8qiqkqb2of16bjr89h4dfvd9roqu@4ax.com>, Bart Lateur wrote:
>>
>>  my $count = () = $user =~ m/[$comp]/g;
>>
>
>Addendum: there has been some heavy discussion on the Perl6 mailing list
>around the request of adding a "list" keyword. It turns out that this is
>a grey area in perl, there's no way to uniquely define what exactly it
>would do in all cases, especially in combination with "scalar".
>Therefore it won't be added. You'll have to help yourself with various
>workarounds, like this one, which all behave slightly different in
>border cases. You can check the Perl6 archives.

However, I just realized that, if the desired behavior is indeed the one
shown above -- no-op list context, count elements in scalar context --
then the code for a list() function is stunningly simple:

  sub list { @_ }

-- 
Ilmari Karonen - http://www.sci.fi/~iltzu/
Please ignore Godzilla / Kira -- do not feed the troll.


------------------------------

Date: Fri, 23 Mar 2001 23:29:02 GMT
From: tjla@guvfybir.qlaqaf.bet (Gwyn Judd)
Subject: Re: every 15 seconds
Message-Id: <slrn9bnn1s.53t.tjla@thislove.dyndns.org>

I was shocked! How could Tom Scheper <tom@power.net.uk>
say such a terrible thing:
>On Fri, 23 Mar 2001 09:40:11 -0600, Daniel Berger <djberge@uswest.com>
>shed a beam of light on us:
>
>>Bjoern Kaiser wrote:
>>
>>> how do i output something every 15 seconds?
>>
>>while(1){
>>   print "Hello World!\n";
>>   sleep(15);
>
>Ahh.. But what if print "Hello World!" is replaced with something that
>takes several seconds to complete, but at other times just
>miliseconds?

Here's a method using sleep and piped open that solves this problem, but
it only really works well if the length of time for the "something" is
generally much less than the length of time between outputs. This is
because of the way <> determines whether a line has been read:

#!/usr/bin/perl -w
use strict;

sub output
{
    print "Hello, world!\n";
    sleep rand 2;
}

my $pid = open CHLD, "-|";

defined $pid or die "Couldn't fork: $!";

if ($pid != 0)
{
    while (<CHLD>)
    {
        print;
        sleep 8;
    }
}
else
{
    for (1..5)
    {
        output;
    }
}

-- 
Gwyn Judd (print `echo 'tjla@guvfybir.qlaqaf.bet' | rot13`)
Good news is just life's way of keeping you off balance.


------------------------------

Date: Fri, 23 Mar 2001 23:58:39 GMT
From: cfedde@fedde.littleton.co.us (Chris Fedde)
Subject: Re: every 15 seconds
Message-Id: <PqRu6.212$T3.189345792@news.frii.net>

In article <m1y9twumfs.fsf@halfdome.holdit.com>,
Randal L. Schwartz <merlyn@stonehenge.com> wrote:
>>>>>> "Rich" == Rich  <bigrich318@yahoo.com> writes:
>
>Rich> use strict;
>
>Rich> for (1..4){
>Rich> my $before = time;
>Rich> my $output = &delayed_output;
>Rich> my $after = time;
>Rich> sleep(15-int($after-$before));
>Rich> print $output.' / Displayed-'.scalar(localtime())."\n";
>Rich> }
>
>Rich> sub delayed_output {
>Rich> #delay up to 10 seconds
>Rich> my $delay = int(rand(11));
>Rich> sleep($delay);
>Rich> return "Delayed ".$delay." seconds-".scalar(localtime());
>Rich> }
>
>This would be simpler, and sleeps until the even multiples of 15 seconds:
>
>    while (1) {
>      sleep 15 - time % 15;
>      ... do task here ...
>    }
>

Which could be a disadvantage for designs that don't want to sleep
if "do task here" takes longer than 15 seconds.

chris
-- 
    This space intentionally left blank


------------------------------

Date: 23 Mar 2001 19:03:14 -0600
From: logan@cs.utexas.edu (Logan Shaw)
Subject: Re: every 15 seconds
Message-Id: <99groi$56u$1@boomer.cs.utexas.edu>

In article <o5tmbtke9bclmclnue5rs25aj12cg0bv0d@4ax.com>,
Tom Scheper  <tom@power.net.uk> wrote:
>On Fri, 23 Mar 2001 09:40:11 -0600, Daniel Berger <djberge@uswest.com>
>shed a beam of light on us:
>>while(1){
>>   print "Hello World!\n";
>>   sleep(15);
>
>Ahh.. But what if print "Hello World!" is replaced with something that
>takes several seconds to complete, but at other times just
>miliseconds?

Actually, there are some good arguments for leaving it like that if
making it happen precisely every 15 seconds is not a strict
requirement.

The first reason is that the most obvious reason for the process to
take longer than normal is if the machine is heavily loaded.  In that
case, you might like to have the process occur less frequently to keep
from increasing the load on the machine as much.

The other reason only applies if you have several jobs going at once
with the same interval.  Basically, if you make the jobs run at a fixed
interval, they will have no chance to naturally spread out the times
they run so that they are not all idle at the same time and all
demanding the CPU at the same time.  But, if you put a fixed delay
between them, then this can happen.

Here's a Perl script to demonstrate that:

	#! /usr/local/bin/perl

	sub delay_loop
	{
		my ($iterations) = @_;
		my ($before, $after, $i);

		$| = 1;

		print "iterations=$iterations\r";

		$before = time;

		for ($i = 0; $i < $iterations; $i++)
		{
		}

		$after = time;

		return ($after - $before);
	}

	sub calibrate
	{
		my ($calibrate_limit) = @_;

		my ($elapsed, $iterations);

		print "calibrating delay loop\n";

		$iterations = 1;
		while (($elapsed = delay_loop($iterations))
				<= $calibrate_limit)
		{
			$iterations *= 2;
		}

		print "\n";
		print "rate=", $iterations / $elapsed, "\n";

		return ($iterations / $elapsed);
	}

	sub spin
	{
		my ($seconds, $calibration) = @_;

		my ($iterations, $i);

		$iterations = int($calibration * $seconds);

		for ($i = 0; $i < $iterations; $i++)
		{
		}
	}

	sub be_a_child
	{
		$| = 1;

		for ($i = 0; $i < $cycles; $i++)
		{
			print "$$ working #$i\n";
			spin ($calibration, $work);
			print "$$ sleeping\n";
			sleep $nap;
		}

		exit (0);
	}

	$nap = 10;
	$work = 1;
	$jobs = 7;
	$cycles = 25;
	$calibrate_limit = 10;
	$calibration = calibrate ($calibrate_limit);

	print "\n";
	print "starting the fun...\n";

	for ($i = 0; $i < $jobs; $i++)
	{
		if (fork > 0)
		{
			be_a_child;
		}
	}

Of course, this turned out to be a longer script than I thought, but it
was fun anyway...

  - Logan
-- 
whose?  my  your   his  her   our   their   _its_
who's?  I'm you're he's she's we're they're _it's_


------------------------------

Date: Fri, 23 Mar 2001 18:41:30 -0600
From: "Hunter's Shooting Association" <info@HunterShooter.com>
Subject: eXtropia - good tools?
Message-Id: <99gpu0$136$1@news.chorus.net>

I'm rebuilding my site and planning a *major* update.  That means I'm in the
market for serious software.

So far I'm impressed with the WebWare 2.0 suite by eXtropia.com (Selena
Sol's new archive)  It includes every tool that I can imagine.  While I'm
far from an expert programmer, the documentation looks superb and the coding
appears robust (extensive code reusability via Object Oriented design)

Anyone have good or bad comments about eXtropia?

I've also heard good things about http://www.arsdigita.com

Thoughts??

Fast X,
John M. Buol Jr.
Director, HSA
-----------------------------------
Hunter's Shooting Association - http://www.HunterShooter.com
    Free hunting and shooting resources for you!
Articles and eBooks - http://www.HunterShooter.com/news
On-line Hunting-Shooting Events - http://www.huntershooter.com/netmatch
HSA E-zine - subscribe for free - http://www.HunterShooter.com/subscribe
    Or click and send email
mailto:newsletters@huntershooter.com?subject=SUBSCRIBE_HSANews





------------------------------

Date: Sat, 24 Mar 2001 00:33:28 GMT
From: bogus@erol.com (---Pete---)
Subject: Re: Hmmm... Which PERL Book Is Best Suited For This???
Message-Id: <3abbeae0.122448111@news.earthlink.net>

On Fri, 23 Mar 2001 16:04:32 GMT, cfedde@fedde.littleton.co.us (Chris
Fedde) wrote:

>Sounds to me like you want the online perl manual that came with
>your installaton. 
------
Doesn't  work as expected, I installed the 5.0 version that came with
the SAMS book and then uninstalled that and got the 5.6 version
only to get the same errors and frustrations. See below for actual
screen output when several "perldoc" commands tried.

E:\Perl>perldoc
Usage: perldoc.bat [-h] [-r] [-i] [-v] [-t] [-u] [-m] [-n program]
[-l] [-F] [-X
] PageName|ModuleName|ProgramName
       perldoc.bat -f PerlFunc
       perldoc.bat -q FAQKeywords

The -h option prints more help.  Also try "perldoc perldoc" to get
acquainted with the system.

E:\Perl>perldoc -f read
Incorrect DOS version

E:\Perl>perldoc -f read()
No documentation for perl function `read()' found

E:\Perl>perldoc read
No documentation found for "read".

E:\Perl>


> If you are not comfortable working with the
>manual pages using the perldoc command then you can go to one of
>the web resources such as http://www.cpan.org/doc/manual/html/pod/perl.html
-------
Yes, I've tried those too.
They are not very useful. 
Example.. I wanted to know what is... $!
HTML Perldocs say... System calls also set the special $!
Not a very good explanation and it was difficult to locate too.


>For printed matter you can do worse than get the Camel book by Wall, et al.
-----
Chris, I will put this book on my list of books to explore.
Thank you!

---pete---



------------------------------

Date: Sat, 24 Mar 2001 00:33:55 GMT
From: bogus@erol.com (---Pete---)
Subject: Re: Hmmm... Which PERL Book Is Best Suited For This???
Message-Id: <3abbeb6d.122589727@news.earthlink.net>

On 23 Mar 2001 16:35:51 GMT, mlush@hgmp.mrc.ac.uk (Mr. M.J. Lush)
wrote:

>You could get the O'Reilly CD-ROM bookshelf (not a bad deal 
>IMHO you get Perl in a Nutshell, Learning Perl, Learning Perl on 
>Win32 Systems, Programming Perl, Advanced Perl, Programming Perl 
>Cookbook in a searchable format,  as well a paper copy of Perl in a 
>Nutshell for the price of 1.5 books...)
-----
Sounds like a great library to have, however, to understand where I'm
coming from, my intent is not to become an expert PERL programmer
but rather to be able to grab a sample PERL script and be able to
tweak it to do exactly what I need it to do. The books that I find
most useful are organized or indexed such that I can quickly locate
a desired function, operator or whatever, and then have it explain
what it is and used for, the proper syntax,  some examples, and a few
important notes about the practical usage or related topics.

When I go to purchase a book I'll bring a list of "tests" to perform
to evaluate the books themselves. I'll grab several books off the
shelves go sit down and look up my "test" topics. If I can't locate
the topic within a few minutes using the CONTENTS or INDEX, it fails
the test and immediately goes back to the shelf. Once I have 2-3 
books that passed that test, I'll read the appicable sections to see
which book does the best job of explaining the topic. The winner is
the book I purchase.

---pete---




------------------------------

Date: Sat, 24 Mar 2001 00:34:15 GMT
From: bogus@erol.com (---Pete---)
Subject: Re: Hmmm... Which PERL Book Is Best Suited For This???
Message-Id: <3abbeb88.122616352@news.earthlink.net>

On Fri, 23 Mar 2001 10:23:41 -0600, Daniel Berger <djberge@uswest.com>
wrote:

>The Camel Book, while an excellent reference, is not a great teaching book IMO,
>it's way too dry - though you definitely ought to buy it.  Probably the best
>book is the Perl Cookbook.
-------
This makes sense becasue for any new language I've learned, 
I usually have a favorite "reference" book and a favorite
"instructional" book that I use most often.


>There is a chapter on CGI, but its not the focus of the book by any means.  For
>that, I recommend either the "Official Guide to Programming with CGI.pm" by
>Lincoln Stein or O'Reilly's "CGI Programming with Perl".
-------
Yeah, I'll probably end up with 3 books due to my CGI requirements.


>For a book that "does it all", see "Mastering Perl 5" (I forget the publisher).
-----
OK, Dan, thanks for all the good recomendations!


---pete---



------------------------------

Date: Fri, 23 Mar 2001 22:59:37 GMT
From: montep@about.com (Monte)
Subject: Re: How can I read a file backwards?
Message-Id: <3abbd4d5.40941781@news.hal-pc.org>

On Fri, 23 Mar 2001 14:11:01 -0800, Kira <callgirl@la.znet.com> wrote:

>Daniel Berger wrote:
> 
>> ...a line at a time, without putting the entire file into memory?
>> Is this possible?
>
 .....>>  Anyone have any ideas or suggestions?  Thanks in advance.
>
>There is an exceptionally efficient way to handle this although
>it requires one instance of inefficiency and a sacrifice of
>some disk space.
>
>Create a duplicate of your file, backwards. Otherwords, two files
>are available, one forward, one backwards. Your program then makes
>a decision which to use.
>
>I use this method extensively for Natural Language Emulation,
>to run both tree branching and root branching, as needed for
>specific circumstances. When one of my numerous data files
>is updated, modified in some way, a special program runs
>which reads in the entire file, as a slurped array. This
>array is reversed and a 'backwards' file is created. This
>is the single instance of inefficiency; using slurp.
>
>I have found having two versions of a file with which to work,
>is more efficient than programming to read a file backwards,
>significantly more efficient, with larger backwards reads.
>Tradeoff in this case, is greater efficiency gained by a 
>sacrifice of disk space. This doubled use of disk space is
>an equitable exchange with most of my files being under
>one-hundred kilobytes, averaging about fifty kilobytes.
>
>Godzilla!

I would have bet, considering your past approaches to solving perlish
problems, that you'd have simply turned your computer upside down and
then had it read the file.
!!!!!!!! it's a joke. son. I say a joke!







f your gonna spam.....

admin@loopback, $LOGIN@localhost, $LOGNAME@localhost,
$USER@localhost, $USER@$HOST, -h1024@localhost, root@mailloop.com
root@localhost, postmaster@localhost, admin@localhost, abuse@localhost
Chairman Reed Hundt: rhundt@fcc.gov
Commissioner James Quello: jquello@fcc.gov
Commissioner Susan Ness: sness@fcc.gov
Commissioner Rachelle Chong: rchong@fcc.gov
US Postal Service: customer@email.usps.gov
Fraud Watch: fraudinfo@psinet.com
Pyramid Schemes: pyramid@ftc.gov
Federal Trade Commission: consumerline@ftc.gov
net-abuse@nocs.insp.irs.gov


------------------------------

Date: Fri, 23 Mar 2001 17:15:25 -0800
From: Kira <callgirl@la.znet.com>
Subject: Re: How can I read a file backwards?
Message-Id: <3ABBF52D.B116B1D1@la.znet.com>

Monte wasted bandwidth and individual's time with idiocy:
 
> Kira provided helpful information:
> >Daniel Berger asked for help:

(snipped)

> I would have bet, considering your past approaches to
> solving perlish problems, that you'd have simply turned
> your computer upside down and then had it read the file.
> !!!!!!!! it's a joke. son. I say a joke!


(snipped 19 lines of idiotic uncut signature spam)


How delightful. Another spam posting ignorant hateful troll.


Godzilla!


------------------------------

Date: Sat, 24 Mar 2001 00:35:03 +0000 (UTC)
From: efflandt@xnet.com (David Efflandt)
Subject: Re: Problem with sockets and name based virtual host
Message-Id: <slrn9bnqtj.f8e.efflandt@efflandt.xnet.com>

On 23 Mar 2001 15:37:29 GMT, John Michael <johnm@aiamail.com> wrote:
>Hi
>I am trying to connect to a remote server using sockets and the server is
>apache setup using name based virtual host(multiply host are sharing an ip
>number).
>
>The script does work on ip based virtual host setups.
>
>How can I get it to work for name based.

Correct your headers (see below).

>sub open_tcp {
> my ($remote, $add, $port) = @_;
>
>      if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
>       die "No port specified." unless $port;
>
>      my $iaddr   = inet_aton($remote)               || die "Could not find
>host: $remote";
>      my $paddr   = sockaddr_in($port, $iaddr);
>      my $proto   = getprotobyname('tcp');
>      socket(SOCK, PF_INET, SOCK_STREAM, $proto)  || die "Socket Error: $!";
>      connect(SOCK, $paddr)    || die "Connect Error: $!";
>
> my $old_fh = select(SOCK);
> $| = 1;
> select($old_fh);

Anything after the first blank line is the end of the headers, which in
your case is the first line (\n\n).  Therefore your Host: header is never
sent.  Try putting the "\n\n" at the end of the LAST header.  Better yet,
use "\015\012" in place of each "\n" per webget in perldoc perlipc.

>     print SOCK "GET $add HTTP/1.0\n\n";
>      print SOCK "Host: $remote\n";
>      print SOCK "Connection: Keep-Alive\n";
>      print SOCK "User-Agent: Real Time Scripts Agent/1.0\n";
>      print SOCK "Content-type: application/x-www-form-urlencoded\n";
>}

The above Content-type line should not be there, lose it.

-- 
David Efflandt  efflandt@xnet.com  http://www.de-srv.com/
http://www.autox.chicago.il.us/  http://www.berniesfloral.net/
http://cgi-help.virtualave.net/  http://hammer.prohosting.com/~cgi-wiz/


------------------------------

Date: Fri, 23 Mar 2001 17:28:54 -0700
From: "Zac Hester" <zhester@enetis.net>
Subject: Question: Addressing Strings?
Message-Id: <3abbe7fa$1@news.enetis.net>

Here's a quick question about strings in Perl...

I'm trying to use strings like character arrays.  Okay, I know, I know, Perl
is a string oriented language.  That's all I've heard from Perl programmers
for quite a while now, but there's got to be a solution.  If I can use the
'index' function to return a substring's position in a string, shouldn't
there be an inverse of that function that returns a substring based on a
position (or positions)?

I've looked far and wide, and no one can give me an answer except for their
reasons why such a function doesn't exist.  I've already been yelled at for
suggesting that Perl should have a simple method for addressing each
character in a string, so I hope I'm not offending any of the Perl gods by
asking this question.

If you think you can help, or would like to know the circumstances of my
delemna, email me:
zhester(ATsymbolGOEShere)enetis.net
or respond to this post.

Thanks in advance,
Zac Hester




------------------------------

Date: 24 Mar 2001 00:31:29 GMT
From: Eli the Bearded <elijah@workspot.net>
Subject: Re: Question: Addressing Strings?
Message-Id: <eli$0103231928@qz.little-neck.ny.us>

In comp.lang.perl.misc, Zac Hester <zhester@enetis.net> wrote:
> I'm trying to use strings like character arrays.  Okay, I know, I know, Perl
> is a string oriented language.  That's all I've heard from Perl programmers
> for quite a while now, but there's got to be a solution.  If I can use the
> 'index' function to return a substring's position in a string, shouldn't
> there be an inverse of that function that returns a substring based on a
> position (or positions)?

You got something against substr?

> I've looked far and wide, and no one can give me an answer except for their
> reasons why such a function doesn't exist.  I've already been yelled at for
> suggesting that Perl should have a simple method for addressing each
> character in a string, so I hope I'm not offending any of the Perl gods by
> asking this question.

Well, people here aren't going to like that you didn't say why substr
is wrong. Inline::C should make it easy to access perl strings like C
strings, if you really like that sort of thing.

Elijah
------
use Inline C=>qq<#include <string.h>\nSV*japh(){char*JAPH="Just Another>
 .qq< Perl Hacker\\n";return newSVpv(JAPH,strlen(JAPH)+1);}>;print japh()


------------------------------

Date: 23 Mar 2001 19:22:28 -0600
From: logan@cs.utexas.edu (Logan Shaw)
Subject: Re: Question: Addressing Strings?
Message-Id: <99gssk$5da$1@boomer.cs.utexas.edu>

In article <eli$0103231928@qz.little-neck.ny.us>,
Eli the Bearded  <elijah@workspot.net> wrote:
>In comp.lang.perl.misc, Zac Hester <zhester@enetis.net> wrote:
>> I'm trying to use strings like character arrays.  Okay, I know, I know, Perl
>> is a string oriented language.  That's all I've heard from Perl programmers
>> for quite a while now, but there's got to be a solution.  If I can use the
>> 'index' function to return a substring's position in a string, shouldn't
>> there be an inverse of that function that returns a substring based on a
>> position (or positions)?
>
>You got something against substr?

Or if you really want to use all of Perl's list operations on a
string's characters, one can always do this:

	@array = split (//, $string);

and then this:

	$string = join ("", @array);

to put it back together again.  It's not the most efficient thing
in the world, but it's nice if you want to, say, concisely figure
out which characters occur in a file:

	open (FOO, "/etc/passwd") or die;
	$file_as_string = join ("", <FOO>);
	close FOO;

	@char_array = split (//, $file_as_string);

	%found = map ( ($_ => 1), @char_array );
	print map ("'$_'\n", sort keys %found);

Hope that helps.

  - Logan
-- 
whose?  my  your   his  her   our   their   _its_
who's?  I'm you're he's she's we're they're _it's_


------------------------------

Date: Fri, 23 Mar 2001 23:32:04 GMT
From: "John Hall" <jhall@ifxonline.com>
Subject: regexp exception confusion
Message-Id: <U1Ru6.64915$o7.2753526@news1.rdc1.sdca.home.com>

Apologize for my last question.. Had simply misplaced an item in the wrong
part of a loop... [can I say it happens to the best of us without being
pegged by rotten eggs?]

This one is confusing; I am searching a $var for each of the words in an
array using a foreach loop. For the most part the thing works fine, but for
one of the words it's not finding it. I am using /.+$var.+/ so the word
should be matched no matter what's in front or behind, but if there is a '
or a " in front of _this one specific word_ then it doesn't match! My
demonstration code follows, followed by my output:

________________________________________________
#!/usr/bin/perl


dbmopen(%datadb,"datadb", 0644) or die "dbmopen: $!";

$datadb{_NAUGHTY_} = ( 'bob, willis, butt, weasel, olives');

@naughty = split /,/, $datadb{_NAUGHTY_};


print $datadb{_NAUGHTY_};
print "\n";

print @naughty;
print "\n";
untie %datadb;



$newtext = <<HTML;

    This text consists mainly of olives good stuff, but an occasional butt
might pop up unexpectedly.
    Also, you are a little "weasel "bob. olives

HTML

print $newtext;
print "\n";

foreach $badword(@naughty) {

        if ($newtext =~ /.*($badword).*/) { print "found $1\n"; }

       }
________________________________________________

bob, willis, butt, weasel, olives
bob willis butt weasel olives

    This text consists mainly of olives good stuff, but an occasional butt
might pop up unexpectedly.
    Also, you are a little "weasel "bob. olives


found bob
found  butt
found  olives
________________________________________________

Notice 'weasel' is conspicuously missing, even though bob also has a
quotation mark in front of it and still works.. I've also tried /.*$var.*/
in my regexp.. no dice.






------------------------------

Date: Sat, 24 Mar 2001 11:26:05 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Statistics
Message-Id: <slrn9bnqct.ugg.mgjv@martien.heliotrope.home>

On Fri, 23 Mar 2001 15:19:44 +0100,
	Jonas Nilsson <jonni@ifm.liu.se> wrote:
> "Bernard El-Hagin" <bernard.el-hagin@lido-tech.net> wrote in message
> news:slrn9bmccn.s3u.bernard.el-hagin@gdndev32.lido-tech...
>> More than it used to be when?
> 
> More than a month ago?

Find all articles of Greg Bacon, with the subject 'Statistics for
comp.lang.perl.misc'. Look at the line that says:

Articles: 1272 (543 with cutlined signatures)

This only gives you weekly summaries, but it'll tell you whether the
volume has increased. If you want more accuracy, look at your local
newsspool, and summarise the articles by date. Hopefully your admin
keeps a long enough history to say anything meaningful about it.

The oldest article I've got in my spool is 26725, from Dec 22. The
latest is 42346 from March 24. That could give you some avaerage over
that whole period to compare current figures to.

Martien
-- 
Martien Verbruggen              | 
Interactive Media Division      | Useful Statistic: 75% of the people
Commercial Dynamics Pty. Ltd.   | make up 3/4 of the population.
NSW, Australia                  | 


------------------------------

Date: Sat, 24 Mar 2001 01:24:56 +0000 (UTC)
From: abigail@foad.org (Abigail)
Subject: Re: Statistics
Message-Id: <slrn9bntr8.p30.abigail@tsathoggua.rlyeh.net>

Martien Verbruggen (mgjv@tradingpost.com.au) wrote on MMDCCLXII September
MCMXCIII in <URL:news:slrn9bnqct.ugg.mgjv@martien.heliotrope.home>:
\\ On Fri, 23 Mar 2001 15:19:44 +0100,
\\ 	Jonas Nilsson <jonni@ifm.liu.se> wrote:
\\ > "Bernard El-Hagin" <bernard.el-hagin@lido-tech.net> wrote in message
\\ > news:slrn9bmccn.s3u.bernard.el-hagin@gdndev32.lido-tech...
\\ >> More than it used to be when?
\\ > 
\\ > More than a month ago?
\\ 
\\ Find all articles of Greg Bacon, with the subject 'Statistics for
\\ comp.lang.perl.misc'. Look at the line that says:
\\ 
\\ Articles: 1272 (543 with cutlined signatures)
\\ 
\\ This only gives you weekly summaries, but it'll tell you whether the
\\ volume has increased. If you want more accuracy, look at your local
\\ newsspool, and summarise the articles by date. Hopefully your admin
\\ keeps a long enough history to say anything meaningful about it.
\\ 
\\ The oldest article I've got in my spool is 26725, from Dec 22. The
\\ latest is 42346 from March 24. That could give you some avaerage over
\\ that whole period to compare current figures to.


I once wrote a program that goes out to deja, grabs all the those
articles, and graphs the usage, caching the results in a dbm file.

Deja is no more, but it shouldn't be too hard to adapt it for google.


Here it is:


#!/opt/perl/bin/perl -w

#
# $Id: stats.pl,v 1.1 1999/12/20 21:40:28 abigail Exp abigail $
#
# $Log: stats.pl,v $
# Revision 1.1  1999/12/20 21:40:28  abigail
# Initial revision
#

use strict;
use LWP::Simple;
use AnyDBM_File;
use POSIX;
use Date::Calc qw /Delta_Days Add_Delta_Days/;

my $db      =  '/home/abigail/Perl/stats';
my $plot    =  '/usr/local/bin/gnuplot';
my $display =  '/usr/local/bin/display';

my  %db;
tie %db     =>  AnyDBM_File => $db, O_CREAT | O_RDWR, 0644;

unless (@ARGV) {
    my $server  =  'www.deja.com';
    my $subject =  'Statistics for comp.lang.perl.misc';
    my $author  =  'Greg Bacon';
    my $group   =  'comp.lang.perl.misc';
    my $from    =   strftime ("%d %b %Y", localtime 0);
    my $to      =   strftime ("%d %b %Y", localtime);

    my $start   =  "http://$server/[ST_rn=ps]/qs.xp?ST=PS&svcclass=dnyr&QRY=&defaultOp=AND&DBS=1&OP=dnquery.xp&LNG=english&subjects=$subject&groups=$group&authors=$author&fromdate=$from&todate=$to&showsort=date&maxhits=100";

    $start      =~  y/ /+/;

    my @pages   = ($start);
    my @fetches = ();

    while (@pages) {
        my $url  = shift @pages;
        my $text = get $url or die "Failed to retrieve $url.\n";

        while ($text =~ m{<td>\s*(\d+)\s*/\s*(\d+)\s*/\s*(\d+)\s*</td>\s*
                          <td><b>\s*
                          <a\s+href\s*=\s*("[^"]*")>\s*
                               Statistics\s+for\s+comp\.lang\.per}gx) {
            push @fetches => [$3, $1, $2, $4];   # year, month, date, link.
        }

        push @pages => $1 
              if $text =~ m{<a\s+href\s*=\s*"([^"]*)">\s*next\s+messages};
    }

    foreach my $t (@fetches) {
        my  $date =  sprintf "%04d/%02d/%02d" => @$t [0 .. 2];
        next if defined $db {$date};
        my  $text =  get $t -> [3] or die "Failed to fetch $t->[3]\n";
            $text =~ m{<a\s+href\s*=\s*"([^"]+)">
                            View\s+original\s+Usenet\s+format</a>}x;
            $text =  get $1 or die "Failed to fetch $1\n";
        my ($posters)  = $text =~ /Posters:\s*(\d+)/;
        my ($articles) = $text =~ /Articles:\s*(\d+)/;
        my ($volume)   = $text =~ /Volume\s+generated:\s*(\d+(?:\.\d*)?)\s*kb/;

        $db {$date} = join "," => $posters, $articles, $volume;

        print "$date: $db{$date}\n";
    }
}


my $fdate = '9999/99/99';
my $ldate = '0000/00/00';
my %max   = (posters  => 0,
             volume   => 0,
             articles => 0);

my @list;
while (my ($date, $info) = each %db) {
    my @info = split /,/ => $info;

    $fdate          = $date     if $date     lt $fdate;
    $ldate          = $date     if $date     gt $ldate;
    $max {posters}  = $info [0] if $info [0]  > $max {posters};
    $max {articles} = $info [1] if $info [1]  > $max {articles};
    $max {volume}   = $info [2] if $info [2]  > $max {volume};

    push @list => [$date, @info];
}

# Normalize.
my $volume_ratio = $max {articles} / $max {volume};
my $poster_ratio = $max {articles} / $max {posters};
map {$_ -> [3]  *= $volume_ratio;
     $_ -> [1]  *= $poster_ratio} @list;

# Work around a rounding bug in gnuplot by extending the displayed range
# if necessary. This rounding error might be highly platform dependend.
my  $min_diff = 457;
my  $diff  = Delta_Days (split (m {/} => $fdate), split (m {/} => $ldate));
if ($diff  < $min_diff) {
    $ldate = sprintf "%04d/%02d/%02d" =>
                       Add_Delta_Days (split (m {/} => $fdate), $min_diff);
}

@list = sort {$a -> [0] cmp $b -> [0]} @list;

my $tfdate = sprintf "%02d/%02d/%04d" => reverse ($fdate =~ /(\d+)/g);
my $tldate = sprintf "%02d/%02d/%04d" => reverse ($ldate =~ /(\d+)/g);

local *PLOT;
open   PLOT, "| $plot | $display" or die "Failed to open pipe: $!\n";
# open   PLOT, "> /tmp/plot" or die;

$" = " ";
print PLOT <<PLOT;

# Driver.
set terminal  png small color

# Title for the graphs.
set title    "Perl statistics $tfdate - $tldate"

# We have dates on the x-axis.
set xdata     time

# Formats for the tics.
set format x "%d/%m/%y"
set format y "%.0f"

# Labels.
set ylabel   "Articles"
set y2label  "Posters"
set y2range  [0:$max{posters}]

# Tics.
set ytics     border nomirror norotate
set y2tics    border nomirror norotate

# Grid.
set grid      xtics ytics

# Format of dates in the data.
set timefmt  "%Y/%m/%d"

# First the ranges, than the plots.
plot ["$fdate":"$ldate"] [0:$max{articles}]         \\
      '-' using 1:2 smooth unique title 'Posters',  \\
      '-' using 1:3 smooth unique title 'Articles', \\
      '-' using 1:4 smooth unique title 'Volume'
@{[map {"@$_\n"} @list]}
e
@{[map {"@$_\n"} @list]}
e
@{[map {"@$_\n"} @list]}
e
PLOT
close PLOT or die "Failed to close pipe: $!\n";

__END__

=pod

This program is copyright 1999 by Abigail.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

=cut


------------------------------

Date: Fri, 23 Mar 2001 23:49:34 GMT
From: Dan Sugalski <dan@tuatha.sidhe.org>
Subject: Re: Threaded Perl on FreeBSD
Message-Id: <iiRu6.58167$Ok4.4810274@news1.rdc1.ct.home.com>

Mike Stevens <tick1@my-deja.com> wrote:
> Thanks for the reply Dan.  make test fails with: lib/posix ...... Failed
> at test 10.  If I cd to the t directory, and run ./TEST, it fails with
> the same error.  Running ./perl lib/posix.t gives me:

[Snip with test 9 and 10 swapped]

> So is the 'test' successful or not?

Yup, looks fine.

> I'm building the threaded perl to use with PerlMx, a sendmail milter
> program,  Thanks again,

Didn't realize there was stuff out there that would use perl threaded
this way yet. Keen.

				Dan


------------------------------

Date: Fri, 23 Mar 2001 17:35:48 -0700
From: "Zac Hester" <zhester@enetis.net>
Subject: Re: use CGI error
Message-Id: <3abbe998$1@news.enetis.net>

Hey,

I found you're problem:  I don't think I've ever seen anyone try to
concatenate strings with a comma before...

print "Content-type: text/html", "\n\n";

should be:

print "Content-type: text/html" . "\n\n";

or, more simply:

print "Content-type: text/html\n\n";

This is important, 'cuz the browser needs to know what's comming.

Hope this helps,
Zac Hester


"Cosmic Cruizer" <c_cruizer@my-deja.com_nospam> wrote in message
news:Xns906D6D21079ADccruizermydejacom@207.126.101.100...
> I am getting the dreaded 500 Server Error
> Error: HTTPd: malformed header from script
>
> I am trying to execute the following simple script to find out why I am
> having errors with using CGI.pm:
> ------------------------
> #!/usr/bin/perl
>
> use lib '/usr/libdata/perl5/site_perl';
> use CGI;
>
> print "Content-type: text/html", "\n\n";
>
> print "<HTML>\n<HEAD>\n";
> print "<TITLE>Please Correct Errors</TITLE>\n";
> print "</HEAD>\n";
> print "<BODY>\n";
> print "<H1>Please Correct These Errors</H1>\n";
> print "</BODY>\n</HTML>";
> ------------------------
>
> If I comment out both the use lib and CGI lines, it executes ok. CGI.pm is
> located in the "use lib" path and perms on CGI.pm is set to 444 and the
> site_perl directory is set to 755.
>
> Any suggestions?




------------------------------

Date: Sat, 24 Mar 2001 00:59:25 +0000 (UTC)
From: efflandt@xnet.com (David Efflandt)
Subject: Re: use CGI error
Message-Id: <slrn9bnsba.f8e.efflandt@efflandt.xnet.com>

On Fri, 23 Mar 2001, Cosmic Cruizer <c_cruizer@my-deja.com_nospam> wrote:
>I am getting the dreaded 500 Server Error
>Error: HTTPd: malformed header from script
>
>I am trying to execute the following simple script to find out why I am 
>having errors with using CGI.pm:

Your file permissions are correct (755 dir/444 CGI.pm).  Did you upload
your script in ASCII mode (not binary)?  If possible to test it in the
shell, does it run as "./scriptname.cgi" ("perl scriptname.cgi" would not
reveal some errors).  Maybe your path or root is different on the
web.  Try this test instead:

#!/usr/bin/perl -w
print "Content-type: text/plain\n\n";
use lib '/usr/libdata/perl5/site_perl';
foreach (@INC) {
    if (-r "$_/CGI.pm") {
        print "Found readable $_/CGI.pm\n";
        exit;
    }
}
print "Can't find CGI.pm\n\n\@INC contains:\n";
foreach (@INC) { print "$_\n"; }
print "Current dir: ", `pwd`, "\n";

-- 
David Efflandt  efflandt@xnet.com  http://www.de-srv.com/
http://www.autox.chicago.il.us/  http://www.berniesfloral.net/
http://cgi-help.virtualave.net/  http://hammer.prohosting.com/~cgi-wiz/


------------------------------

Date: 23 Mar 2001 19:24:05 -0600
From: logan@cs.utexas.edu (Logan Shaw)
Subject: Re: use CGI error
Message-Id: <99gsvl$5e1$1@boomer.cs.utexas.edu>

In article <3abbe998$1@news.enetis.net>, Zac Hester <zhester@enetis.net> wrote:
>I found you're problem:  I don't think I've ever seen anyone try to
>concatenate strings with a comma before...
>
>print "Content-type: text/html", "\n\n";
>
>should be:
>
>print "Content-type: text/html" . "\n\n";

I suggest that you try the code that you are saying doesn't work.

If that doesn't make it clear, think about this:

	@list = ("Content-type: text/html", "\n\n");
	print @list;

  - Logan
-- 
whose?  my  your   his  her   our   their   _its_
who's?  I'm you're he's she's we're they're _it's_


------------------------------

Date: Sat, 24 Mar 2001 01:25:09 -0000
From: c_cruizer@my-deja.com_nospam (Cosmic Cruizer)
Subject: Re: use CGI error
Message-Id: <Xns906DB11143E0Accruizermydejacom@207.126.101.100>

That's pretty interesting. Depending on which book I use (I'm new to cgi 
and perl), there is either a comma or nothing at all. I never noticed it 
until you pointed it out. Unfortunately, the problem still occurs 
regardless of which way is written. The comma, period or nothing at all 
work fine as long as the use lib and use CGI lines are commented out. None 
of them work if the lines are un-commented.

Thanks anyway... especially since you shed new light on a different issue I 
was unaware of.

Cos

"Zac Hester" <zhester@enetis.net> wrote in <3abbe998$1@news.enetis.net>:

>Hey,
>
>I found you're problem:  I don't think I've ever seen anyone try to
>concatenate strings with a comma before...
>
>print "Content-type: text/html", "\n\n";
>
>should be:
>
>print "Content-type: text/html" . "\n\n";
>
>or, more simply:
>
>print "Content-type: text/html\n\n";
>
>This is important, 'cuz the browser needs to know what's comming.
>
>Hope this helps,
>Zac Hester


------------------------------

Date: Fri, 23 Mar 2001 23:08:01 GMT
From: Uri Guttman <uri@sysarch.com>
Subject: Re: using closures (road to OO)
Message-Id: <x7lmpw13u6.fsf@home.sysarch.com>

>>>>> "WK" == W K <b_nospam_ill.kemp@wire2.com> writes:

  >> The OP's code contained no anonymous subs.


  WK> .. coz I didn't want one

then you don't want a closure. 

  >> The perlsub manpage addresses the OP's question:

yes it does. particularly the part about BEGIN

  >> {
  >> my $secret_val = 0;
  >> sub gimme_another {
  >> return ++$secret_val;
  >> }
  >> }


  WK> there isn't an anonymous subroutine there. Its called gimme_another.

there is some argument about whether closures must be anonymous or
not. i say they must be so you can generate multiple instances each with
different private data. so what you want is just a normal named sub with
a private initialized static var which is what the quoted doc addresses.

  WK> I have been reading damien conway's oo perl book.  This  stuff is on p 56
  WK> and 57.

damian calls that closures and i disagree. but his comment about
anonymous subs and closure being much more powerful is on target. 

  WK> its the "man with dress on and a funny hat" book. (what's that
  WK> cover all about?)

manning chose the cover image. ask them.

uri

-- 
Uri Guttman  ---------  uri@sysarch.com  ----------  http://www.sysarch.com
SYStems ARCHitecture, Software Engineering, Perl, Internet, UNIX Consulting
The Perl Books Page  -----------  http://www.sysarch.com/cgi-bin/perl_books
The Best Search Engine on the Net  ----------  http://www.northernlight.com


------------------------------

Date: 23 Mar 2001 19:12:32 -0600
From: logan@cs.utexas.edu (Logan Shaw)
Subject: Re: Wild Card Search!!
Message-Id: <99gsa0$5c0$1@boomer.cs.utexas.edu>

In article <3ABBABCF.7AE488C3@alcatel.com>,
Clinton Munden  <clinton.munden@alcatel.com> wrote:
>I have a search script and here is the problem.  If I do a wild card
>search ( * ) I get a server error.   Right now, as a work around, I have
>add the following code
>
>$value =~ tr/*/a/;
>
>this allows the search to continue without error.  But it is not a good
>solution because if I do a wild card search like this for example (
>help* ), then the above code replaces the * with a and searches for
>"helpa"  which obviously give no search results.  Does anyone know some
>short code to deal with the wild card character?

Are you using these search strings in a regular expression?

If so, "*" isn't the wildcard character.  It's the "this
pattern should match if the preceding thing occurs zero
or more times" character, which is not the same thing.

Anyway, if you'd like to eliminate metacharacters
from a regular expression, you can do this:

	$pattern = quotemeta $pattern;

If you'd like users to be able to enter "*" to act like a wildcard
(i.e. "match zero or more characters"), you can do this:

	$pattern = quotemeta $pattern;
	$pattern =~ s/\\\*/.\*/g;

Then you could safely do something like this:

	print "<P><H1>The results are...</H1></P>";
	print "<P><PRE>";
	print grep (/$pattern/, @some_text);
	print "</PRE></P>";

Actually, that's pretty terrible style since the
output of "grep" should be HTML escaped.  (What if
it contained "<applet...>"?)  But you get the idea.

  - Logan
-- 
whose?  my  your   his  her   our   their   _its_
who's?  I'm you're he's she's we're they're _it's_


------------------------------

Date: 16 Sep 99 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 16 Sep 99)
Message-Id: <null>


Administrivia:

The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc.  For subscription or unsubscription requests, send
the single line:

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

| NOTE: The mail to news gateway, and thus the ability to submit articles
| through this service to the newsgroup, has been removed. I do not have
| time to individually vet each article to make sure that someone isn't
| abusing the service, and I no longer have any desire to waste my time
| dealing with the campus admins when some fool complains to them about an
| article that has come through the gateway instead of complaining
| to the source.

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.

For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V10 Issue 557
**************************************


home help back first fref pref prev next nref lref last post