Reputation: 701
I found an example of some Perl code I needed, but it had something in it that I didn't recognise.
my $i //= '08';
I can't find any reference to this anywhere! It appears to be the same as:
my $i = '08';
Am I missing something?
Upvotes: 39
Views: 14671
Reputation: 385655
Short answer: It's the same as my $i = '08';
. You probably wanted $i //= '08';
.
First, let's look at $i //= '08';
EXPR1 //= EXPR2;
is the same as
EXPR1 = EXPR1 // EXPR2;
except that EXPR1 is only evaluated once. It's a convenient way of writing
EXPR1 = EXPR2 if !defined(EXPR1);
See perlop for documentation on Perl operators.
Back to my $i //= '08';
. That means
my $i;
$i = '08' if !defined($i);
but $i
will always be undefined in that situation. It would be far better to write
my $i = '08';
But, the code was probably supposed to be
$i //= '08'; # no `my`
Upvotes: 7
Reputation: 203
It's almost the same as ||
, except that it checks if $i
is defined, not just true.
Upvotes: 4
Reputation: 753625
The //=
operator is the assignment operator version of the //
or 'logical defined-or' operator.
In the context of a my
variable declaration, the variable is initially undefined so it is equivalent to assignment (and would be better written as my $i = '08';
). In general, though,
$i //= '08';
is a shorthand for:
$i = (defined $i) ? $i : '08';
It is documented in the Perl operators (perldoc perlop
) in two places (tersely under the assignment operators section, and in full in the section on 'logical defined-or'). It was added in Perl 5.10.0.
Upvotes: 65
Reputation: 1364
It is "defined-or" operator.
$i //= '08';
is equivalent to:
$i = defined($i)? $i: '08';
It was introduced in Perl 5.10.0, and not supported by older versions.
Upvotes: 6
Reputation: 5210
$i //= '08'
is the same as $i = defined($i) ? $i : '08'
.
It's almost the same as $i ||= '08'
, which translates to $i = $i ? $i : '08'
.
Now, when you declare your variable with my
, it's set to undef
. Thus, it will always follow the 08
branch.
Also, in case you're wondering, the //
operator appeared in the Perl v5.10; so it would generate a compilation error on the older Perls.
Upvotes: 5