Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is //= in Perl?

Tags:

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?

like image 792
Upland Avatar asked Dec 12 '12 18:12

Upland


People also ask

What does $_ mean in Perl?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }

What is $/ in Perl?

From the Perl Doc. $/ and $\ which are the input and output record separators respectively. They control what defines a "record" when you are reading or writing data. By default, the separator used is \n .

What does %variable mean in Perl?

Variables are the reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.


2 Answers

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.

like image 195
Jonathan Leffler Avatar answered Oct 07 '22 08:10

Jonathan Leffler


Short answer: It's the same as my $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. It would be far better to write

my $i = '08'; 
like image 36
ikegami Avatar answered Oct 07 '22 09:10

ikegami