"Perl for Perl Newbies" - Part 2Useful Functionssplit

9.1. split

The split function can be used to split a string according to a regular expression. The syntax of the split function is as follows:

@components = split(/$regexp/, $string);

Here's a simple example that retrieves the user-id of a given username:

use strict;
use warnings;

my ($line, @parts);

my $user_name = shift;

open my $in, "<", "/etc/passwd";
while ($line = <$in>)
{
    @parts = split(/:/, $line);
    if ($parts[0] eq $user_name)
    {
        print $user_name . "'s user ID is " . $parts[2] . "\n";
        exit(0);
    }
}
close($in);

print $user_name . "'s user ID was not found!\n";
exit(-1);

The following code splits a sentence into words and prints them:

use strict;
use warnings;

my $sentence = shift;

my @words = split(/\s+/, $sentence);

my $i;
for($i=0;$i<scalar(@words);$i++)
{
    print "$i: " . $words[$i] . "\n";
}

Written by Shlomi Fish