Monty wrote:
I'm reading "Network Programming with Perl" by Lincoln Stein, and I've
come across a snippet of code I'mnot quite following:

open (WHOFH, "who |") or die "Can't open who: $!";

While (<WHOFH>) {

'While' is an error. What the code probably said was 'while' (Perl is case sensitive.)

This reads each "line" from the file/pipe where "line" is defined by the Input Record Separator $/ and the current "line" is stored in the $_ variable.

    next unless /^(\S+)/;

The current line is matched against the regular expression /^(\S+)/ which says that the beginning of the line must start with one or more non-whitespace characters and those non-whitespace characters are captured by the parentheses into the $1 variable. If the current line does not match the pattern the next loops back to the start and another line is obtained.


    $who{$1}++;

If the pattern matched we get to this point where the captured string is used as the key of the %who hash and the value of that key is incremented.


}

It's the 'next' line I'm unclear on.  I know that results: parse the
first field from each output line of the 'who' command, but I'm
wondering why this might have been done in this way.  It seems to me
that the 'next' line states "get the next record unless the current
one startes with a non-whitespace character".

The UNIX 'who' command output lines always start with non-whitespace
characters, as far as I can see.  It seems just as sensible to leave
this line out.  Does anyone know additional value to doing this?

You should never use the numeric variables like $1 unless you are sure that the pattern matched otherwise the value in $1 will be left over from a previous successful match so this ensures that $1 always has a valid value.


Also, the '$who{$1}++' lines has the same effect here as "awk '{ print
$1 }'",

In perl "awk '{ print $1 }'" would be written as "perl -lane'print $F[0]'"


and leads me to believe that $2, $3, etc. also exist, but that
doesn't seem to be the case as I've tried printing those variables.
How does the '$1' work in this case?

perldoc perlre

You have to have sets of parentheses for each numeric variable.



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.                            -- Larry Wall

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to