in reply to How to get split $var to work like split ' '?

You'll need to use an if statement:

my $split_pattern //= getOpt(); my @x; unless( defined $split_pattern ) { @x = split ' ', $line; } else @x = split $split_pattern, $line; }

Not elegant, but the only way. The special behaviour of split ' ', is triggered by the use of exactly ' ' in the source code.

Substituting a variable set to a space, or even a conditional statement where one branch is ' ', will not do the same thing.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: How to get split $var to work like split ' '?
by hdb (Monsignor) on Sep 10, 2013 at 20:19 UTC

    UPDATE: Pls ignore this post. Thanks to LanX above I now understand what the problem is.

    Can you explain what the supposedly special behavior of split ' ' is? I cannot find any documentation saying anything about it. For me this works:

    use strict; use warnings; use Data::Dumper; my $str = "I want a split pattern"; my $pattern = $ARGV[0] // ' '; my @pieces = split /$pattern/, $str; print Dumper \@pieces;
    hdb$ perl split4.pl $VAR1 = [ 'I', 'want', 'a', 'split', 'pattern' ]; hdb$ perl split4.pl a $VAR1 = [ 'I w', 'nt ', ' split p', 'ttern' ];

      You may also want to use quotemeta. e.g.

      ski@anito:~$ perl -e 'use strict; use warnings; my $x = "a.*b.*c.*d"; my $pattern = ".*"; my @x = split /$pattern/, $x; print join " - ",@x'
      ski@anito:~$

      vs.

      ski@anito:~$ perl -le 'use strict; use warnings; my $x = "a.*b.*c.*d"; my $pattern = quotemeta(".*"); my @x = split /$pattern/, $x; print join " - ",@x'
      a - b - c - d
      ski@anito:~$

      perldoc -f quotemeta.
      Search for "specifying a PATTERN of space" in perldoc -f split. The difference relates to leading empty strings.