in reply to shift implicit dereference
G'day Lennotoecom,
"... what that "+" stuff exactly does."
A unary "+" is used for disambiguation. If you were to code ${shift}, that would be ambiguous: did you mean the variable $shift or a dereferencing operation on the value shifted off @_. Using a "+" indicates you meant the shift function and not a variable name. Consider this code:
#!/usr/bin/env perl -l use strict; use warnings; my $shift = 'E'; my @x = \ (qw{A B C D}); test_shift(@x); sub test_shift { print ${+shift}; print ${shift()}; print ${shift @_}; print ${shift(@_)}; print ${shift}; }
Output:
Ambiguous use of ${shift} resolved to $shift at ./junk line 15. A B C D E
You'll find this usage of "+" cropping up in many places. Here's some examples.
Does the "(" following a function name start a list of arguments to the function?
$ perl -Mstrict -Mwarnings -le 'print (1==0) ? "true" : "false"' print (...) interpreted as function at -e line 1. Useless use of a constant ("true") in void context at -e line 1. Useless use of a constant ("false") in void context at -e line 1. $ perl -Mstrict -Mwarnings -le 'print +(1==0) ? "true" : "false"' false
Is "{...}" an anonymous block or a hashref constructor?
$ perl -Mstrict -Mwarnings -MData::Dump -e 'dd [map { my $y = uc; {$y +=> 1} } "a".."c"]' ["A", 1, "B", 1, "C", 1] $ perl -Mstrict -Mwarnings -MData::Dump -e 'dd [map { my $y = uc; +{$y + => 1} } "a".."c"]' [{ A => 1 }, { B => 1 }, { C => 1 }]
How can I tell a constant bareword and a hash key bareword apart?
$ perl -Mstrict -Mwarnings -le 'use constant X => "a"; my %h = (a => 1 +); print $h{X}' Use of uninitialized value in print at -e line 1. $ perl -Mstrict -Mwarnings -le 'use constant X => "a"; my %h = (a => 1 +); print $h{+X}' 1
Documentation for unary "+" usages appears to be rather scattered. For the three pairs of examples above, see "perlop: Symbolic Unary Operators", "perlref: Making References" and "constant: CAVEATS", respectively. There are other examples documented elsewhere. I couldn't locate any references to the ${+shift} example.
-- Ken