From: Monty <[EMAIL PROTECTED]>
> 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}++;
> }
> 
> 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?
> 
> Also, the '$who{$1}++' lines has the same effect here as "awk '{ print
> $1 }'", 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?

The
  next unless /^(\S+)/;
serves two purposes. First it makes sure you do not try to process 
lines that are empty or start with whitespace (whether that's likely 
to happen or not I have no idea) and it captures the first "word" 
from the line so that you can access it via $1.

The magic is in the regular expression

  /^(\S+)/

The \S means "any character except whitespace, the + means one or 
more such characters, the () mean that you are interested in those 
characters and the ^ means that you are searching for thise non-
whitespace characters in the beginning of the string only.

So that line could be read as

  go read the next line if the current one doesn't start with non-
whitespace characters. If it does, remember them in $1.

HTH, Jenda

===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
        -- Terry Pratchett in Sourcery


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


Reply via email to