Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: Help to split

by Athanasius (Archbishop)
on Mar 16, 2013 at 06:19 UTC ( [id://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,

Replies are listed 'Best First'.
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1023813]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (7)
As of 2024-03-19 01:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found