[22822] in Perl-Users-Digest
Perl-Users Digest, Issue: 5043 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Mon May 26 21:06:05 2003
Date: Mon, 26 May 2003 18:05:06 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Perl-Users Digest Mon, 26 May 2003 Volume: 10 Number: 5043
Today's topics:
Re: a Bayesian intelligent e-mail autoresponder? <sardines@purse-seine.net>
An error in my solution code (Steven Danna)
Re: An error in my solution code <usenet@dwall.fastmail.fm>
Re: Code exits after printing data to the browser. (David Efflandt)
Re: drop down selection from flatfile <bwalton@rochester.rr.com>
err...stuck <Anonymous-Remailer@nowhere.com>
Re: err...stuck <noreply@gunnar.cc>
Re: err...stuck <Anonymous-Remailer@nowhere.com>
Re: finding "mailto:" strings in html files (Veky)
Re: Help with errors. <bwalton@rochester.rr.com>
Re: need explanation <johnsmith@yahoo.com>
Re: Perl Nightmare on OS X (Tad McClellan)
Perl on Mac OSX <urrozalf@vcn.bc.ca>
Re: Perl on Mac OSX <Bo@email.replies.accepted.org>
Re: Perl Script to Caluclate Averages? <bwalton@rochester.rr.com>
Re: Perl Script to Caluclate Averages? (Sam Holden)
Re: why key is added to hash after defined ? (Veky)
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Mon, 26 May 2003 19:02:43 +0100
From: Alan Clifford <sardines@purse-seine.net>
Subject: Re: a Bayesian intelligent e-mail autoresponder?
Message-Id: <Pine.LNX.4.53.0305261859340.1181@mundungus.clifford.ac>
On Mon, 26 May 2003, totojepast wrote:
t> Please can you tell me if anybody has tried to use ifile or a similar
t> Bayesian for an automatic e-mail autoresponder?
t>
So how would that work? Would your autoresponse provide a list of words
to be taken out the message and ask the sender to try again?
Alan
( If replying by mail, please note that all "sardines" are canned.
There is also a password autoresponder but, unless this a very
old message, a "tuna" will swim right through. )
------------------------------
Date: 26 May 2003 15:32:28 -0700
From: MissingWords@hotmail.com (Steven Danna)
Subject: An error in my solution code
Message-Id: <e78d8c5a.0305261432.584b5be@posting.google.com>
There is an error in the code I posted previously:
============================
use strict;
use warnings;
use diagnostics;
#Get Perl to help you.
print "Enter numbers to be averaged, ^Z when done\n";
chomp(my @input = <>); # Get numbers from <> and remove newlines.
my $total=0;
my @numbers=undef;
if(@input ==0){die "No numbers to average";} #checking for divide by
0 erros
@numbers = split/\s+/,$_ foreach @input; #splits on white space
$total +=$_ foreach @numbers; #Sum input
print 'The average is ' . $total / @numbers ."\n"
==============================
The code works fine when all the input is given on one line seperated
by whitespace. However, when there is information on multiple lines,
the average is no longer correct. This occured becuase the following
line reasignes the values of @numbers each time through the loop
instead of adding new values to the end of the array:
@numbers = split/\s+/,$_ foreach @input;
My apologizes for posting code before testing it completely.
This should work better:
============================
use strict;
use warnings;
use diagnostics;
#Get Perl to help you.
print "Enter numbers to be averaged, ^Z when done\n";
chomp(my @input = <>); # Get numbers from <> and remove newlines.
my $total=0;
my @numbers;
if(@input == 0){die "No numbers to average";} #checking for divide
by 0 erros
foreach (@input){
my @temp_numbers = split;
push @numbers, @temp_numbers;
}
print "numbers are: @numbers\n"; #Used for debuging--just wanted to
be sure
$total +=$_ foreach @numbers; #Sum input
print 'The average is ' . $total / @numbers ."\n"
================================
If anyone finds any other oddities with the way this behaves please
let me know so I can try to fix them and learn from them.
Steven Danna
------------------------------
Date: Mon, 26 May 2003 23:24:58 -0000
From: "David K. Wall" <usenet@dwall.fastmail.fm>
Subject: Re: An error in my solution code
Message-Id: <Xns9387C581AD1C1dkwwashere@216.168.3.30>
MissingWords@hotmail.com (Steven Danna) wrote:
> use strict;
> use warnings;
> use diagnostics;
> #Get Perl to help you.
>
> print "Enter numbers to be averaged, ^Z when done\n";
> chomp(my @input = <>); # Get numbers from <> and remove newlines.
> my $total=0;
> my @numbers;
> if(@input == 0){die "No numbers to average";} #checking for divide
> by 0 erros
> foreach (@input){
> my @temp_numbers = split;
> push @numbers, @temp_numbers;
> }
> print "numbers are: @numbers\n"; #Used for debuging--just wanted to
> be sure
> $total +=$_ foreach @numbers; #Sum input
> print 'The average is ' . $total / @numbers ."\n"
How about something like this:
use strict;
use warnings;
print "Enter numbers to be averaged, ^Z when done\n";
my @numbers;
push @numbers, grep length, split /\s+/, $_ while <>;
die "No numbers entered\n" unless @numbers;
my $sum = 0;
$sum += $_ for @numbers;
print "Average = ", $sum / @numbers, "\n";
No chomp() or a buffering array needed, just store them as they come in.
The grep() is there to filter out empty fields you would get if an input
line starts with a space.
If I recall correctly from a numerical methods class I took a long time
ago, if some of the numbers are fractions and some are large, they
should be sorted from smallest to largest (in absolute value) before
accumulating the sum so as to avoid rounding errors due to machine
representation. (Someone please correct me if my memory is faulty)
--
David Wall
------------------------------
Date: Mon, 26 May 2003 19:50:05 +0000 (UTC)
From: efflandt@xnet.com (David Efflandt)
Subject: Re: Code exits after printing data to the browser.
Message-Id: <slrnbd4rvd.lb9.efflandt@typhoon.xnet.com>
On Mon, 26 May 2003, David <david@[no_spam]simplymaya.com> wrote:
>
> sub download {
> my $fh = new FileHandle;
> $fh->open("</home/downloads/$tutorial_info[0]");
> my $piece_size = ($rh_fi->{'file_size_bits'} / 60) + 40;
> my $data;
> my $file_offset = ($rh_fi->{'part_size_bits'} -
> $rh_fi->{'part_size_bits'} * $input{'part'});
>
> print "Content-type: application/ipp\n";
> print "Content-length: $rh_fi->{'part_size_bits'}\n";
> print "Content-Disposition: filename=test.zip\n\n";
>
> if ($input{'size'} ne 'Full' && $rh_fi->{'no_parts'} != 1) {
> $fh->seek( ($file_offset - $rh_fi->{'part_size_bits'}),1 );
>
> for (my $loop=0; $loop <= $rh_fi->{'file_size_bits'}; $loop +=
> $piece_size) {
> $fh->read($data, $piece_size,);
> print $data;
> }
> } else {
> $fh->seek(0,1);
>
> for (my $loop=0; $loop <= $rh_fi->{'file_size_bits'}; $loop +=
> $piece_size) {
> $fh->read($data, $piece_size);
> print $data;
> }
> }
>
> &clean_up;
>
> }
>
>
> The clean_up sub is never called, the script seems to exit after the
> print $data statement could someone enlighten me as to why the
> clean_up sub is not executed?
Just guessing that the browser is expecting the content length of bytes,
closes the connecting when that is received, web server recognizes that
stdout is closed and terminates your script.
See 'perldoc perlipc' and search for 'sig' (case insensitive).
--
David Efflandt - All spam ignored 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: Mon, 26 May 2003 22:00:53 GMT
From: Bob Walton <bwalton@rochester.rr.com>
Subject: Re: drop down selection from flatfile
Message-Id: <3ED28DCD.9090108@rochester.rr.com>
Peter Feldmann wrote:
...
> i've written a couple of programms to adminstrate
> network-printers via snmp over a html-interface.
>
> to select a printer i have to enter the hostname or the ip
> in a submit-field and then it work (see program below)
>
> well, as i only know the hostnames and the ips, i want to
> replace the submit-field ($value) by a drop-down which reads a file
> including all ips, hostnames and describtions (just as the /etc/hosts).
>
> can anybody give me the syntax how to read that flatfile and how to select
> one field from it ???
...
> peter
>
> the programm (so far) written for an aix-enviroment
> ----------------------------------------------------
> #!/usr/bin/perl
>
> read(STDIN, $Daten, $ENV{'CONTENT_LENGTH'});
> print "Content-type: text/html\n\n";
> print "<html>\n";
> @Formularfelder = split(/&/, $Daten);
> foreach $Feld (@Formularfelder)
> {
> ($name, $value) = split(/=/, $Feld);
> $value =~ tr/+/ /;
> $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
> $value =~ s/<!--(.|\n)*-->//g;
> $Formular{$value} = $value;
> my $counter = qx(/usr/sbin/snmpinfo -m get -c public -h $value
> mib-2.43.10.2.1.4.1.1| /usr/bin/cut -d ' ' -f3);
> wait();
> my $dis1 = qx(/usr/sbin/snmpinfo -m get -c public -h $value
> 1.3.6.1.4.1.2.6.112.1.1.9.2.11.0| /usr/bin/cut -d ' ' -f3);
> wait();
> my $dis2 = qx(/usr/sbin/snmpinfo -m get -c public -h $value
> 1.3.6.1.4.1.2.6.112.1.1.9.2.6.0| /usr/bin/cut -d ' ' -f3);
> wait();
> my $dis3 = qx(/usr/viega/snmp_display1 $value);
> wait();
> my $dis4 = qx(/usr/viega/snmp_display2 $value);
> wait();
>
> print "<body><table><TR><TD>Druckername:</td>";
> print "<td>$value</td>";
> print "</tr>";
> print "<TR><TD>Zählerstand:</td>";
> print "<td>$counter</td>";
> print "</tr>";
> print "<TR><TD>IP Adresse:</td>";
> print "<td>$dis1</td>";
> print "</tr>";
> print "<TR><TD>Gateway:</td>";
> print "<td>$dis2</td>";
> print "</tr>";
> print "<TR><TD>Display:</td>";
> print "<td>$dis3</td>";
> print "</tr>";
> print "<TR><TD>Display:</td>";
> print "<td>$dis4</td>";
> print "</tr>";
> }
> print "</table></body></html>\n";
...
Well, first of all, when writing a CGI program, you should:
use CGI;
That will get rid of all sorts of bugs, make your coding easier, and
handle properly all the little weird things hardly anyone even knows
about, like specifying character encodings etc.
To do what you want to do, you will want to generate an HTML "select"
block. "option" tags go with the select block. Look this up in an HTML
reference, and then generate the appropriate HTML. Your CGI script will
be presented with a parameter with the name you give to the select
block. If you attempt to use the "multiple" selection option of
"select", you will really wish you had used the CGI module. You will
need to fix your badly-broken parameter decoding (for example, you don't
even look at the parameter name) before it will properly handle another
parameter -- a task the CGI module does automatically.
Or you could just put a bunch of links to your CGI script, with each
link giving the appropriate parameter name and value right in the URL.
Then you wouldn't have to change your CGI script at all.
--
Bob Walton
------------------------------
Date: Mon, 26 May 2003 19:58:31 +0100
From: "just sum1" <Anonymous-Remailer@nowhere.com>
Subject: err...stuck
Message-Id: <ostAa.549$JZ6.111@news-binary.blueyonder.co.uk>
Can someone tell me if im on the right track...
Beneath is a cgi im trying to use, I done what it says (opened a browser,
typed in the url with /cgi-bin/click/admin.cgi
on the end) and no control panel came up...just a 404 error.
What am i missing...Im very new to cgi, so be gentle plz ;)
How to start logging clicks on links
=============================--- -- - -
To start logging clicks on your web site, open admin.cgi in your
web browser. Log into the control panel by supplying your user
name and password.
http://www.yourdomain.com/cgi-bin/click/admin.cgi
--
------------------------------
Date: Mon, 26 May 2003 21:20:29 +0200
From: Gunnar Hjalmarsson <noreply@gunnar.cc>
Subject: Re: err...stuck
Message-Id: <batpvi$3er0a$1@ID-184292.news.dfncis.de>
just sum1 wrote:
> Can someone tell me if im on the right track...
> Beneath is a cgi im trying to use, I done what it says (opened a
> browser, typed in the url with /cgi-bin/click/admin.cgi on the end)
> and no control panel came up...just a 404 error.
What you describe is not a Perl problem, so you are asking in the
wrong news group. This is a URL that may be useful:
http://my.execpc.com/~keithp/bdlogcgi.htm
If that doesn't help, you'd better ask for help in a forum dealing
with CGI scripts.
/ Gunnar
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
------------------------------
Date: Mon, 26 May 2003 21:23:00 +0100
From: "just sum1" <Anonymous-Remailer@nowhere.com>
Subject: Re: err...stuck
Message-Id: <BHuAa.291$Uc.50@news-binary.blueyonder.co.uk>
Ok thanx
--
-------------------------------------------------------------------------
FIGHT BACK AGAINST SPAM!
Download Spam Inspector, the Award Winning Anti-Spam Filter
http://mail.giantcompany.com
"Gunnar Hjalmarsson" <noreply@gunnar.cc> wrote in message
news:batpvi$3er0a$1@ID-184292.news.dfncis.de...
> just sum1 wrote:
> > Can someone tell me if im on the right track...
> > Beneath is a cgi im trying to use, I done what it says (opened a
> > browser, typed in the url with /cgi-bin/click/admin.cgi on the end)
> > and no control panel came up...just a 404 error.
>
> What you describe is not a Perl problem, so you are asking in the
> wrong news group. This is a URL that may be useful:
>
> http://my.execpc.com/~keithp/bdlogcgi.htm
>
> If that doesn't help, you'd better ask for help in a forum dealing
> with CGI scripts.
>
> / Gunnar
>
> --
> Gunnar Hjalmarsson
> Email: http://www.gunnar.cc/cgi-bin/contact.pl
>
------------------------------
Date: Mon, 26 May 2003 19:29:48 +0000 (UTC)
From: veky@cromath.math.hr (Veky)
Subject: Re: finding "mailto:" strings in html files
Message-Id: <batpvc$41p$1@bagan.srce.hr>
Dok je Veky citao comp.lang.perl.misc,
pod PIDom 27288 (290771 off, 428 to go...),
primijetio je kreaturu zvanu clos@trentu.ca (Netware60),
ispod cijih su prstiju izasle (izmedu ostalih) sljedece rijeci:
|thanks for the code... but when I run it i don't get any output when
|I know there should be some. Any suggestions as to what is going
|wrong? Thanks.
|> @ARGV=<*.html>;while(<>){
|> push@spamlist,@f if@f=/"(mailto:[\w@.])"/g
|> };print join"\n",sort@spamlist
Did you run it from the directory in which your HTML files are?
--
\#{% Sad gradi svoj grad iz snova... znaj da mozes i znaj da znas...
------------------------------
Date: Tue, 27 May 2003 00:39:18 GMT
From: Bob Walton <bwalton@rochester.rr.com>
Subject: Re: Help with errors.
Message-Id: <3ED2B2DD.4030400@rochester.rr.com>
Joe Creaney wrote:
>
>
> Bob Walton wrote:
>
>> Joe Creaney wrote:
...
>
> Thanks for the advice. I am starting to get a handle on what the
> problems are. First I was treating an object which is a refrence like
> it was a normal variable. Although there were two variables bointing to
> the name of the objcet there was only one item stored in memory.
Yes, that's always a good one. You can eliminate it by always making
references to anonymous copies of your array, i.e.:
$ref1=[@array1];
...
$ref2=[@array1]; #reference to a different copy of @array.
instead of:
$ref3=\@array2;
...
$ref4=\@array2; #reference to the *same* array
With this, if you execute: $$ref2[3]=4; you will not change @array1[3].
But if you execute $$ref4[3]=4; you will change $$ref3[3] and
$array2[3], since they are all the same array element. In a large
program, this can be an unexpected and extremely hard to locate bug if
it is not what you desired. Your description of things working the
first time but not later would be consistent with instances of this
problem. It should be easy to fix: Look for all occurrences of \@array
and, if it is the thing to do, change to [@array]. There was only one
place where it looked like you might have this problem (sub generate
where @stuff is created and a reference assigned to $bag), but I don't
think you really have the problem there, because the variables are
lexical, and will be freshly recreated the next time generate is
invoked. So even if @stuff hangs around for the duration due to
reference counts, each instance of it will be separate.
>
> This debugging is very confusing. As far as my other errors, I am
> going though my code to try to figure them out. It is tricky because
> the functions work in the beginning but not later on.
It is also possible that your functions work in one case (the cases used
near the beginning), but have bugs that weren't exercised then which are
exercised later. Perhaps generating good test stubs for each function
and really running each one through its paces individually would help.
That way it would be easy to see if each sub generates an appropriate
error message if it is presented with bad input, etc (actually, most of
them don't appear to have any input checks at all). Trying to do them
all at once could be overwhelming.
One other thing I notice is that you have for loops like:
for $i(0..@array){
#do stuff with $array[$i]
}
You are off by one on your terminating index in this case. The last
element in the array is $#array, which is one less than scalar(@array).
I don't know if that could be causing you trouble or not.
...
--
Bob Walton
------------------------------
Date: Mon, 26 May 2003 23:33:37 GMT
From: "Anthony" <johnsmith@yahoo.com>
Subject: Re: need explanation
Message-Id: <3ed2a43d$1@news.syd.ip.net.au>
thanks for everyones input. It does make more sense to me now thati know
what is going on....
Just one other questions
To log the new file name or if any errors occour what is the command???????
"John W. Krahn" <krahnj@acm.org> wrote in message
news:3ED1D038.E5EECD09@acm.org...
> > Anthony wrote:
> >
> > trying to work out this script, and what it means!!!!!!! Can someone
> > explain what is highlighted in purple for me. Am finding it hard to
> > know what it means.
> > Sstill trying to work perl out....
> > Any help would be appreciated
> >
> >
> > my $num = 1;
> > my $filename = "ABCDEFF.TXT";
> > my $time = time();
> > my ($min, $hour, $day, $mon, $year) = (localtime($time))[1..5];
> > $mon++; $year+=1900;
> > $num =
> > $num<10?"0$num":$num;
> > $min = $min<10?"0$min":$min;
> > my $h2 = $hour%10;
> > my $h1 = ($hour - $hour%10)/10;
> > $day = $day<10?"0$day":$day;
> > $mon = $mon<10?"0$mon":$mon;
> > $year = $year%1000;
> >
> > my $stamp = "${num}${day}${mon}${year}${h1}.${h2}${min}";
> >
> > rename($filename, $stamp) or die("RENAME: $!");
>
>
> If you write it like this it may be easier to understand:
>
> my $num = 1;
> my $filename = 'ABCDEFF.TXT';
> my ( $min, $hour, $day, $mon, $year ) = (localtime)[1..5];
> my $stamp = sprintf '%02d%02d%02d%d%d.%d%02d',
> $num, $day, $mon + 1, $year % 100, $hour / 10, $hour % 10,
> $min;
> rename $filename, $stamp or die "RENAME: $!";
>
>
> Or like this:
>
> use POSIX 'strftime';
> my $num = '01';
> my $filename = 'ABCDEFF.TXT';
> my $stamp = strftime "$num%d%m%g%H%M", localtime;
> substr $_, -3, 0, '.';
> rename $filename, $stamp or die "RENAME: $!";
>
>
>
> John
> --
> use Perl;
> program
> fulfillment
------------------------------
Date: Mon, 26 May 2003 17:56:07 -0500
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Perl Nightmare on OS X
Message-Id: <slrnbd56s6.224.tadmc@magna.augustmail.com>
Bob Walton <bwalton@rochester.rr.com> wrote:
> Nick wrote:
>> Global symbol "$foo" requires explicit package name at ./foobar.pl
>> line 5.
>
> That's a message that results because your program includes the line:
>
> use strict;
>
> When use strict is in effect, you must declare all variables, typically
> with the "my" or "our" functions, or you must specify the full name of
> the variable. Even in package main. Package globals cannot be accessed
> without the package name
Yes they can, by using our().
> (using my or our makes the variable a lexical
^^^^^^^^^^^^
> variable, and it is no longer a package global).
That is not true either.
Using my() makes a _new_ variable, having no relationship whatsoever
with any other variable with the same name. After my($foo), the
package variable $foo is still around, it is just harder to access.
Using our() does NOT make a lexical variable. After our($foo) you
are exempted from "use strict"'s requirement to use explicit package
names. The variable is still a package variable, what is lexical is
the _exemption_ from stricture complaints.
>> I must assign $foo as $main::foo, even if I state
>>
>> package main;
>>
>> at the beginning of a script.
Not if you also say:
our $foo;
>> I thought that is a package weren't
>> assigned, it was assumed it belonged to main.
No, it is in whatever your _current_ package is.
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: Mon, 26 May 2003 23:36:11 +0000 (UTC)
From: "Alfonso G. Urroz" <urrozalf@vcn.bc.ca>
Subject: Perl on Mac OSX
Message-Id: <bau8db$1sn$1@luna.vcn.bc.ca>
Hi there, I am trying to learn PERL on my own, using the Terminal feature
available on Mac OSX. I am using the famous "Camel Book", and nothing
seems to work.
First I tried the following:
time > script1
date >> script1
Then I typed:
cat script1
The system answered:
time
date
as expected
Then I typed:
chmod +x script1
Then I typed:
script1
The system answered:
scriptq is not a command, or something like that.
Can anyone help me, on what should I do, to make this thing work, or where
to learn more on Perl on the Mac?
Any help, will be appreciated.
Thanks.
Alfonso G. Urroz
urrozalf@vcn.bc.ca
------------------------------
Date: Tue, 27 May 2003 00:47:28 GMT
From: "Bruce Fournier" <Bo@email.replies.accepted.org>
Subject: Re: Perl on Mac OSX
Message-Id: <AAyAa.1031264$S_4.1040445@rwcrnsc53>
looks like you're doing a shell script ..
try adding these lines to a file:
#!/usr/bin/perl
$systime = localtime;
print "$systime\n";
then from shell prompt:
chmod +x filename
then ./filename
"Alfonso G. Urroz" <urrozalf@vcn.bc.ca> wrote in message
news:bau8db$1sn$1@luna.vcn.bc.ca...
> Hi there, I am trying to learn PERL on my own, using the Terminal feature
> available on Mac OSX. I am using the famous "Camel Book", and nothing
> seems to work.
>
> First I tried the following:
> time > script1
> date >> script1
>
> Then I typed:
> cat script1
>
> The system answered:
> time
> date
> as expected
>
> Then I typed:
> chmod +x script1
>
> Then I typed:
> script1
>
> The system answered:
> scriptq is not a command, or something like that.
>
> Can anyone help me, on what should I do, to make this thing work, or where
> to learn more on Perl on the Mac?
>
> Any help, will be appreciated.
>
> Thanks.
>
> Alfonso G. Urroz
> urrozalf@vcn.bc.ca
>
------------------------------
Date: Mon, 26 May 2003 21:19:02 GMT
From: Bob Walton <bwalton@rochester.rr.com>
Subject: Re: Perl Script to Caluclate Averages?
Message-Id: <3ED28400.5000908@rochester.rr.com>
Spread Eagle wrote:
...
> I don't need an entire script, just a line or two of code that I can
> understand, mainly the variable ($_ I assume) that holds the value
> entered by the user and increments it with each subsequent number the
> user enters, then a line that will divide the running total by "n" to
> give a running average on the fly.
>
> I played with the script you gave me and it doesn't work, at least
> when I pasted it into a script file.
>
> But let me ask you a few questions about it:
>
The supplied script (and all the others so far posted) is obfuscated. I
will put up a simple one with commentary at the end.
>
>>undef $/;
>>
> I assume that's some kind of scaler declaration. What's its purpose?
This sets Perl variable $/ to the undefined value. $/ is the "record
separator string" and, when set to undef, causes Perl to read to end of
file as a single string. As it will in the next line.
>
>
>>$_ = <>;
>>
> I understand that. It puts the keyboard entry into the variable $_
>
>
>>s/^\s*//;
This does a regexp match and replace (substitution) on the default
variable. The first non-blank after the s is the delimiter, in this
case a / . The ^\s* is a regexp (regular expression). This one starts
matching at the beginning of the string in $_ (^), and will match zero
or more occurrences (*) of whitespace (\s) until no more whitespace is
found. Assuming this match is successful (it will always be), the
whitespace that was matched is replaced with nothing. So this deletes
all the leading whitespace in $_.
>>
> what is s/?
The substitution operator.
> ^ denotes the beginning of a string, right?
> \s means whitespace, right?
> * is multiplication?
Nope. * in this context means "repeat zero or more times".
> what is //?
The delimiter for the substitution operator (s).
>
>
>>s/\s*$//;
This is another substitution. This one matches all the whitespace (\s*)
which preceeds the end of the string ($), and replaces it with nothing.
So this deletes all the whitespace at the end of $_.
>>
>
>>$c = s/\s+/+/g + 1;
This contains another substitution (s/\s+/+/g). The one matches one or
more (+) whitespace characters (\s) in the default variable ($_), and
replaces them with a single + (+). The "g" switch tells the
substitution operator to repeat the match/replace over and over until is
fails. The substition operator returns the number of successful
matches, which in this case is one less than the number of numbers. So
1 is added to that result to give the number of numbers, and that is
stored in $c.
>>
> Please explain the right side. What is g?
>
>
>>print eval($_)/$c,"\n";
eval is a Perl function which evaluates a string as a Perl expression,
and returns the value of the last Perl statement executed. In this
case, the string will be something like 1+2+3+4+5 for example. That
would evaluate to 15 . That is divided by the number of numbers in $c
to give the average.
>>
> what is eval? Does it have internal meaning to perl?
>
> Thanks.
>
> Spread Eagle
>
Here is a non-obfuscated commented complete example:
use strict; #always use strict during development
use warnings; #always use warnings during development
my $sum=0; #declare and initialize a variable to hold the sum
my $count=0; #declare and initialize a variable to count numbers
#note: the DATA filehandle reads lines following the __DATA__
while(<DATA>){ #read each line of input until end-of-file
#note: technically, one should remove the newline on the
#end of each line with chomp; here, but it is not necessary
#in this case, as the numeric conversion will ignore the
#newline.
$sum+=$_; #add the numeric value of each line to the sum
$count++; #increment the count
}
my $average=$sum/$count; #compute the average
#note: \n in a "-delimited string is a newline character
#Also, a scalar variable name in a "-delimited string is
#substituted in, or 'interpolated'.
print "The average is $average\n"; #print the answer
__DATA__
1
2
3
4
5
HTH.
--
Bob Walton
------------------------------
Date: 27 May 2003 00:43:59 GMT
From: sholden@flexal.cs.usyd.edu.au (Sam Holden)
Subject: Re: Perl Script to Caluclate Averages?
Message-Id: <slrnbd5d6e.t0h.sholden@flexal.cs.usyd.edu.au>
On Mon, 26 May 2003 21:19:02 GMT, Bob Walton <bwalton@rochester.rr.com> wrote:
[snip explanation of my only a joke code]
>
> Here is a non-obfuscated commented complete example:
>
> use strict; #always use strict during development
> use warnings; #always use warnings during development
> my $sum=0; #declare and initialize a variable to hold the sum
> my $count=0; #declare and initialize a variable to count numbers
> #note: the DATA filehandle reads lines following the __DATA__
> while(<DATA>){ #read each line of input until end-of-file
> #note: technically, one should remove the newline on the
> #end of each line with chomp; here, but it is not necessary
> #in this case, as the numeric conversion will ignore the
> #newline.
> $sum+=$_; #add the numeric value of each line to the sum
> $count++; #increment the count
> }
> my $average=$sum/$count; #compute the average
> #note: \n in a "-delimited string is a newline character
> #Also, a scalar variable name in a "-delimited string is
> #substituted in, or 'interpolated'.
> print "The average is $average\n"; #print the answer
> __DATA__
> 1
> 2
> 3
> 4
> 5
Maybe I'm the only one, but I find those comments actually obfuscate the code...
I'm probably just getting too old now, but I can't seperate the code from the
comments without lots of concentration which doesn't leave much brain left
for actually understanding the code :)
I suggest more whitespace between the code and the comments and lining up the
starting #s of comments on consecutive lines.
There's also the dreaded "$i++; #increment i" type comment, but of course these
comments are in fact designed to help those who don't have a complete
understanding of syntax so I guess that it's fair game here :)
--
Sam Holden
------------------------------
Date: Mon, 26 May 2003 19:28:28 +0000 (UTC)
From: veky@cromath.math.hr (Veky)
Subject: Re: why key is added to hash after defined ?
Message-Id: <batpss$8dq$1@bagan.srce.hr>
Dok je Veky citao comp.lang.perl.misc,
pod PIDom 27288 (291026 off, 432 to go...),
primijetio je kreaturu zvanu Matija Papec <mpapec@yahoo.com>,
ispod cijih su prstiju izasle (izmedu ostalih) sljedece rijeci:
|>|Cool, kaj se od jezika najvise preferira, C?
|>OMG... are you aware of which group we are on:-?
|>You think mentioning C will pass unnoticed because of Croatian:-? :-))
|Um, how careless of me. Did I mention C?, no, actually I don't even know
|what C is.
LOL. :-)
--
\#{% Sad gradi svoj grad iz snova... znaj da mozes i znaj da znas...
------------------------------
Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin)
Subject: Digest Administrivia (Last modified: 6 Apr 01)
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.
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 5043
***************************************