On 7/5/07, Monty <[EMAIL PROTECTED]> 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>) {
next unless /^(\S+)/;
$who{$1}++;
}
That should be "while", not "While"; you probably know that perl is
case-sensitive. But the rest of it looks like something Dr. Stein
might write.
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?
I believe Dr. Stein was using that line primarily to capture the
username at the beginning of the line, ensuring that the pattern match
succeeds. Another programmer might do that like this:
unless (/^(\S+)/) {
warn "unexpected data from 'who' command: '$_', continuing";
next;
}
This program makes noise where the other was silent, but only when it
encounters somebody's unusual (buggy?) who command. If it didn't have
the warning, it would be close to what's in the book.
Also, the '$who{$1}++' lines has the same effect here as "awk '{ print
$1 }'",
Well, yessss, that's true except that it's not. But I think you're
just talking about $1 here.
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?
There's one memory variable for each pair of memory parentheses in the
last successful pattern match. This one has only one pair, so it has
only $1. The others, $2 and so on, are all undef. You can have $42 if
you have 42 pairs of memory parentheses in your pattern, but in that
case please don't ask me to help maintain your code. In any case, the
perlre manpage has the details.
In general, it's poor form to use $1 and friends except shortly after
a successful pattern match, so likewise it's poor form not to check
the result of the pattern match, even if you're sure it will succeed.
Hope this helps!
--Tom Phoenix
Stonehenge Perl Training
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/