Getting one variable from a string using Perl's split command


In perl, say you've got a string like so:

$string = "pmccartney:x:603:603:mccartney,paul:/home/pmccartney:/bin/bash";

And say you just want the value in the fifth field. In perl, to extract just that value, without defining variables for all the other fields which you don't care about, use the following syntax:

$var = (split ":",$string)[4];

Note that the array elements start counting at zero. You can also extract more than just one variable using the same syntax. Consider the following:

#!/usr/bin/perl -w
#
# split_using: Using perl's split function
# The important part here is the syntax and use of the
# third parameter with the split function, since it allows
# you to split a string, but assign only specific parts to
# variables.  This allows you to avoid getting warnings about
# having created variables that were never used (because you
# don't care about those parts of the string).

$phrase = "How I wish you were here";

# Here we split the string, using a space as the delimiter.
# Note the placement of the ( on the right side BEFORE the split command

($first,$third) = (split " ", $phrase) [0,2];
print "Original phrase is $phrase\n";
print "first is $first, third is $third\n";
### End of script ###

When the script is run, we get the following:

$ ./split_using
Original phrase is How I wish you were here
first word is How, third word is wish

02/22/2006