in reply to split and join, what's the clever way to do it

my ($var1, $var2, $var3, $var4, $var5) = split /\|/, $line, 5;
See split

Update: Changed split to use /\|/ instead of '|'. Thanks for pointing it out.

Replies are listed 'Best First'.
Re^2: split and join, what's the clever way to do it
by ikegami (Patriarch) on Jan 27, 2008 at 03:55 UTC

    You've introduced a bug. The first arg of split is a regex even if you obfuscate that fact by using quotes, so the | needs to be escaped:

    split '|', $line, 5; # WRONG split '\\|', $line, 5; # ok split /\|/', $line, 5; # Better split qr/\|/', $line, 5; # Can also use qr// split $re, $line, 5; # or compiled regexes

    Other useful syntaxes:

    my @rec = = split /\|/, $line, 5;
    my %rec; @rec{qw( var1 var2 var3 var4 var5 )} = split /\|/, $line, 5;
      Having been bitten by that myself, are there any documents explaining why split behaves this way rather than the (IMO more sensible) alternative of splitting on a regex if it's /specified as a regex/ and splitting on a plain string if it's 'specified as a plain string'?
        That would have prevented the dynamic construction of split regex patterns in the pre-qr// world, and backwards compatibility prevents us from doing that now (whether it's wise or not).
        Not just split; =~ EXPR is implicitly a match operation using the result of EXPR as the regex. Though the tendency to use quotes instead of // for split, e.g. split "\t" seems to have introduced more confusion about split's operand. (Well, that and the special split " " mode.)
Re^2: split and join, what's the clever way to do it
by Fletch (Bishop) on Jan 27, 2008 at 03:51 UTC

    The first argument to split is a regex, not a string. It makes a difference.

    $ perl -le '$line = "a|b|c|d"; print "-- $_:\n", join( "\n", split( $_ +, $line ) ) for ( qr/\|/, "|" )' -- (?-xism:\|): a b c d -- |: a | b | c | d

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.