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

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;

Replies are listed 'Best First'.
Re^3: split and join, what's the clever way to do it
by dsheroh (Monsignor) on Jan 27, 2008 at 18:25 UTC
    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.)