Upland Upland - 8 months ago 48
Perl Question

What is //= in Perl?

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?

Answer Source

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.