There are a few things I "know" about Perl:
- lists flatten
- functions take and return lists
So if I have this:
sub my_test {
my @x = qw(a b c);
my @y = qw(x y z t);
return (@x, @y);
}
say my_test; # a b c x y z t
say scalar my_test;
I expect either of two result values:
7
, because that's how many items there are in the listqw(a b c x y z t)
. Indeed, this is what I get fromscalar sub { @{[ qw(a b c x y z t) ]} }->()
.'t'
, because if you interpret the commas as the comma operator (sigh) you get('a', 'b', 'c', 'x', 'y', 'z', 't')
which evaluates to't'
. Indeed, this is what I get fromscalar sub { qw(a b c x y z t) }->()
.
What you do get instead is… 4, without warning. Why did I get a mix of list flattening and comma operator?
Similar story with hashes and this rather popular pattern:
sub default_override_hash {
my %defaults = (foo => 'bar', egg => 'quuz');
my %values = @_;
my %overrides = (__baz => '');
return (%defaults, %values, %overrides);
}
scalar default_override_hash; # '1/8'
How does scalar
know that default_override_hash
returned three hashes, and it should not only just get %overrides
(and not everything, and not ''
), but its scalar representation as a hash?