ernix
ernix

Reputation: 3643

What does determine scalar/list context of `split`?

According to perlsecret, the goatse operator =()= provides a list context so that it can count the number of its elements. I used to think that too. But when I accidentally use the operator along with split, I noticed something strange.

The first two lines of following, are exact same statements written in Effective Perl Programming, 2nd edition. But as a matter of fact, it seems split changes behavior by the left side.

my $wc;
$wc = () = "foo:bar:buz" =~ m/(\w+)/g;  # => 3
$wc = () = split /:/, "foo:bar:buz";   # => 1

$wc = (undef) = split /:/, "foo:bar:buz";   # => 2
$wc = (undef, undef) = split /:/, "foo:bar:buz";   # => 3
$wc = (undef, undef, undef) = split /:/, "foo:bar:buz";   # => 3

Could someone tell me what makes the changes of return values?

Upvotes: 2

Views: 108

Answers (1)

choroba
choroba

Reputation: 241798

It's documented in split further down where LIMIT is discussed:

when assigning to a list, if LIMIT is omitted (or zero), then LIMIT is treated as though it were one larger than the number of variables in the list;

It's an optimization so Perl doesn't create values it would then throw away immediately. Just imagine $varX instead of undef.

To avoid this optimization, specify a limit of -1:

$wc = () = split /:/, "foo:bar:buz", -1;

because

If LIMIT is negative, it is treated as if it were instead arbitrarily large; as many fields as possible are produced.

Upvotes: 3

Related Questions