While looking at some Perl code, I came across the assignment of the output of chr directly to a hash:
local %str = chr(shift);
Confused that the code worked fine, this made me realise the following:
perl -le 'my $jurso = 23; print $jurso;'
23
perl -le 'my %jurso = 23; print %jurso;'
23
perl -le 'my @jurso = 23; print @jurso;'
23
I expected that assigning a scalar directly to a hash or an array to result in an error. Can someone explain why the jurso variable behaves like a scalar regardless of the sigil used?
Thanks.
Two words: context matters. It's easier to understand what's going on here if you turn warnings
on:
> perl -wle 'my %jurso = 23; print %jurso;'
Odd number of elements in hash assignment at -e line 1.
Use of uninitialized value $jurso{"23"} in print at -e line 1.
23
In other words, the first statement of your code creates a hash from a single-item list. It's not a good sign (as hashes should usually have an even number of elements in the source list), hence the first warning. Still, a hash is created: it has one element, addressed with a key 23
, and value of this element is undef
.
The second statement attemtps to print this hash, it echoes a key first (23), then its value. It's undef
, as you remember, hence the second warning. Still, this value is printed out - as an empty string. )
With arrays, you won't even have warnings:
> perl -wle 'my @jurso = 23; print @jurso;'
23
... as the first statement fills @jurso
array with a single item, the second statement just prints this array. Again, the context matters.