ghenry has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

Just a quickie. I think the answer is that the while loop is going through the file twice?

--------------
Code that does what I expect, i.e. prints out the 42 lines of my passwd file, with array spaces swapped for <was :> and runs on $_:

#!/usr/bin/perl use strict; use warnings; $" = '<was :>'; open PASSWD, "/etc/passwd" or die "Eh? ($!)"; while (<PASSWD>) { my @passwds = split /:/; print "@passwds"; }

--------------
This now only prints 21 lines? I am not sure why? It misses the odd ones.

#!/usr/bin/perl use strict; use warnings; $" = '<was :>'; open PASSWD, "/etc/passwd" or die "Eh? ($!)"; while (<PASSWD>) { my @passwds = split /:/, <PASSWD>; print "@passwds"; }
Walking the road to enlightenment... I found a penguin and a camel on the way..... Fancy a yourname@perl.me.uk? Just ask!!!

Replies are listed 'Best First'.
Re: Understanding split in a while loop
by saskaqueer (Friar) on Feb 28, 2005 at 12:46 UTC
    while (<PASSWD>) { my @passwds = split /:/, <PASSWD>; }

    Note that you've used <PASSWD> twice. This will skip the even-numbered lines of the file, not the odd-numbered. This is because you read a second line from the file each time inside the loop, splitting on that value. Therefore, your first line that is read from the file (read into $_ in the while() loop) is more or less being discarded.

      I thought that was it. Thanks. So it discards the odd numbered ones, i.e. line 1 etc.

      Thanks.

      Walking the road to enlightenment... I found a penguin and a camel on the way..... Fancy a yourname@perl.me.uk? Just ask!!!

        It doesn't discard them; it places them into $_ but you ignore it.</pedant>