Saturday, July 9, 2011

Perl Tricks: Splitting Strings and Selecting Columns in One Step

Understanding the split and Slice Expression

The Code Snippet

Perl
while (<>) {
    chomp;
    print join("\t", (split /:/)[0, 2, 1, 5] ), "\n";
}

What (split /:/)[0, 2, 1, 5] Means
This expression combines splitting a string and extracting an "array slice" into a single, compact step. Under the hood, it is exactly equivalent to doing this:

Perl
my @fields            = split /:/, $_;
my @fields_to_display = ($fields[0], $fields[2], $fields[1], $fields[5]);

In Plain English
The code creates a list by splitting the current line ($_) using a colon (:) as the delimiter. Immediately after splitting, it grabs only the specific elements at indices 0, 2, 1, and 5 from that new list to pass along to the join function.

No comments: