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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.