split function

L

learnperlscripting

I am having a hard time understanding this perl scripting code:

while (<STDIN>) {
chomp;
($user, $gcos) = (split /:/) [0, 4];
($real) = split(/,/, $gcos);
print "$user is $real \n";
}

i do not understand line 3 and 4. could someone please help me out.
much appreciated.
 
B

Ben Morrow

Quoth (e-mail address removed):
I am having a hard time understanding this perl scripting code:

while (<STDIN>) {
chomp;
($user, $gcos) = (split /:/) [0, 4];

This line first calls the split function: perldoc -f split. It's in list
context (we'll see why in a minute), and it defaults to splitting the
string in $_ that we've just read from STDIN.

The (...)[0,4] is a list slice (perldoc perldata, section "Slices"),
which selects the first and fifth of the items returned by split.

These two values are then assigned to the variables $user and $gecos
respectively.
($real) = split(/,/, $gcos);

This is another split, this time specifying what string to split. The
first result is assigned to the variable $real.
print "$user is $real \n";
}

i do not understand line 3 and 4. could someone please help me out.
much appreciated.

The program looks like a rather poor attempt at parsing a Unix passwd
file. There are at least two bugs: the GECOS field should be split on
the pattern /\s*,\s*/ instead, and the real name needs any instance of
'&' replaced with an initial-caps version of $user. The program is not
'strict'-safe: have you read the Posting Guidelines for this group yet?
Also, if it is intended to parse the real /etc/passwd file, it would be
much better to use the getpwent functions and the User::pwent module, so
it works properly on systems that use other passwd facilities such as
NIS.

Ben
 
U

Uri Guttman

l> I am having a hard time understanding this perl scripting code:
l> while (<STDIN>) {
l> chomp;
l> ($user, $gcos) = (split /:/) [0, 4];
l> ($real) = split(/,/, $gcos);
l> print "$user is $real \n";
l> }

l> i do not understand line 3 and 4. could someone please help me out.
l> much appreciated.

split is well documented. run this command:

perldoc -f split

why is your nick learnperlscripting? are you learning perl or offering
to others to learn perl

if you are learning perl you should first learn to look for help in
perl's docs. all the functions and ops are fully documented there.

uri
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top