Here is the same solution broken into separate steps, and with comments added:
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
# splitting on newlines. So, on the first iteration, $line =
# bsulli03:*:32452:5002:barry sullivan,l230,555-6666,:/students/bsulli
while (my $line = <$fh>)
chomp $line; # Remove the trailing newline
# Split the line on the colon character. On the first loop iterati
# @fields = ('bsulli03', # $fields
# '*', # $fields
# '32452', # $fields
# '5002', # $fields
# 'barry sullivan,l230,555-6666,', # $fields
# '/students/bsulli03', # $fields
# '/usr/bin/ksh'); # $fields
# (Note that array indexes start at zero.)
my @fields = split /:/, $line;
# Now split the fifth field (index 4) on the comma character. On t
# loop iteration, @names = ('barry sullivan', 'l230', '555-6666');
my @names = split /,/, $fields;
# Now split the first field (index 0) on the space character. On t
# loop iteration, @first = ('barry', 'sullivan');
my @first = split / /, $names ;
# Print the first name, which on the first loop iteration is 'barr
close $fh or die "Cannot close file '$file': $!";
Hope that helps,
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||