Search code examples
perlsubroutine

Perl - subroutine to translate variables


I wrote the following subroutine:

sub MakeNan {
    my $n = $_;
    if ( $n !~ /^Positive|^Negative/ ) {
            return "N/A";
    }
    else { return "$n"; }
}

I have been calling it in the following context:

open ( FILE, $file);
while (<FILE>) {
    chomp;
    my @a = split("\t", $_);
    my $hr = $a[55];
    $hr = &MakeNan($hr);
    print "$hr\n";
}
close FILE;

Unfortunately, it returns "N/A" for every value it is given despite the fact that there are many instances of values that should return either "Positive..." or "Negative..."

I don't understand what I am doing wrong to make the subroutine return "N/A" each time.


Solution

  • There are several mistakes. $n doesn't contain your argument because the default variable is not your argument. Your regex is wrong. Do this instead:

    sub make_nan {
      my ($n) = @_; # or: my $n = shift;
      return $n =~ /^(Positive|Negative)/ ? $n : 'N/A';
    }
    

    And drop the & when calling your function.

    But then, you don't need a subroutine since all you need is a ternary operator.