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";
}
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:
result : 1 NA 2
A better way would be
my @array2 = map { ($_ eq "")?'NA' : $_ } @array;