Perl Expression Of $_ ||=
1
2
Entering edit mode
11.5 years ago
Tky ★ 1.0k

Dear all, I have a question regarding the following perl expression at the line of

$_ ||= 'NA' for @array;

By running the script, I knew it substitute the empty elements in array to 'NA', However I couldn't understand how this happened.

Hope you can explain this line and much appreciated if any reference could be provided.

The full script is as below for your reference.

$file=shift @ARGV;
open (FILE,$file) or die "could not open the file";
while(<FILE>)
{
    chomp;
    @array=split(/\s/,$_);
    $_ ||= 'NA' for @array;
        foreach $cell(@array)    {print"$cell\t"}
    print"\n";
}
perl • 2.3k views
ADD COMMENT
4
Entering edit mode

This is really a question related to language features and syntatic sugar of Perl an should be better asked elsewhere, e.g. stackoverflow.com or http://www.perlmonks.org/ (there you might find it already). hint: the ||= operator does the same as $_ || $_ = 'NA'.

Also, this is not really a safe way to generally substitute missing values, and shouldn't be used (not only because of explicit use of $_ imo assignments to $_ should be avoided), see the following code:

use strict;
use warnings;
my @array = (1, 0, 2);
$_ ||= 'NA' foreach (@array);
print"@array\n";

result : 1 NA 2

A better way would be my @array2 = map { ($_ eq "")?'NA' : $_ } @array;

ADD REPLY
4
Entering edit mode
11.5 years ago
Tky ★ 1.0k

Dear Michael, thank you for the explanation and the link.

I checked the perlmonk and found the answer. I summarize it below.

The $_ ||= 'NA'  equals to $_ = $_  or 'NA' , which could be rewrite as $_ = $_  || 'NA'  also as $_ ||= 'NA'
which means if $_ is false, 'NA' will be assigned to $_

The operator usage is similar to that add a value to a variable itself, such as $x += 3

I strongly agree that map is a much better way for this situation. Many thanks!

ADD COMMENT

Login before adding your answer.

Traffic: 2495 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6