Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: Help to split

by Athanasius (Monsignor)
on Mar 16, 2013 at 06:19 UTC ( #1023813=note: print w/ replies, xml ) Need Help??


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

Or you can dispense with map by chaining the calls to split:

#! perl use strict; use warnings; print +(split / /, (split /,/, (split /:/)[4])[0])[0], "\n" while <DAT +A>;

Or as a one-liner:

16:05 >perl -pwe "$_ = (split / /, (split /,/, (split /:/)[4])[0])[0] +. qq[\n];" passwd barry sally sparky sammy sally bill bart bill bart cal tom sally phuong cindy olivo bart celia cindy bart 16:05 >

:-)

Hope that helps,

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


Comment on Re^2: Help to split
Select or Download Code
Re^3: Help to split
by semenych (Initiate) on Mar 17, 2013 at 04:28 UTC

    Thanks Athanasius

      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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1023813]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (9)
As of 2014-09-19 14:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (140 votes), past polls