This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Perl Expression Of $_ ||=

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

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;

1 answer

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!

Log in to answer this question.