Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re^3: Help to split

by semenych (Initiate)
on Mar 17, 2013 at 04:28 UTC ( #1023880=note: print w/replies, xml ) Need Help??

in reply to Re^2: Help to split
in thread Help to split

Thanks Athanasius

Replies are listed 'Best First'.
Re^4: Help to split
by Athanasius (Chancellor) on Mar 17, 2013 at 04:39 UTC

    You’re welcome!

    Here is the same solution broken into separate steps, and with comments added:

    #! perl use strict; use warnings; my $file = 'passwd'; open(my $fh, '<', $file) or die "Cannot open file '$file' for reading: + $!"; # The while loop reads one line of the data file at a time by implicit +ly # splitting on newlines. So, on the first iteration, $line = # bsulli03:*:32452:5002:barry sullivan,l230,555-6666,:/students/bsulli +03:/usr/bin/ksh while (my $line = <$fh>) { chomp $line; # Remove the trailing newline # Split the line on the colon character. On the first loop iterati +on, # @fields = ('bsulli03', # $fields[0] # '*', # $fields[1] # '32452', # $fields[2] # '5002', # $fields[3] # 'barry sullivan,l230,555-6666,', # $fields[4] # '/students/bsulli03', # $fields[5] # '/usr/bin/ksh'); # $fields[6] # (Note that array indexes start at zero.) my @fields = split /:/, $line; # Now split the fifth field (index 4) on the comma character. On t +he first # loop iteration, @names = ('barry sullivan', 'l230', '555-6666'); my @names = split /,/, $fields[4]; # Now split the first field (index 0) on the space character. On t +he first # loop iteration, @first = ('barry', 'sullivan'); my @first = split / /, $names [0]; # Print the first name, which on the first loop iteration is 'barr +y' print "$first[0]\n"; } close $fh or die "Cannot close file '$file': $!";

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1023880]
belg4mit tiptoes through the catacombs, muttering something about SSL

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (11)
As of 2018-06-23 14:57 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.