#! 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,
| [reply] [Watch: Dir/Any] [d/l] |