split

Contents | Up | Prev | Next

# 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 I, "<", "/etc/passwd";
    while ($line = <I>)
    {
        @parts = split(/:/, $line);
        if ($parts[0] eq $user_name)
        {
            print $user_name . "'s user ID is " . $parts[2] . "\n";
            exit(0);
        }
    }
    close(I);

    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";
    }

Contents | Up | Prev | Next