I am working on a perl code that reads in a file with various information
(example: ID, value A, value B, value C..Value Z)
The file values are separated by tabs.

I want to only extract the first 3 columns (ID, value A, value B) and output it to another file, but additionally I want to add a 4th column in the output file that calculates the difference between A and B for each line.

This is the code I have so far:

use strict;
use warnings;

my $input;
my $output;
my ($ID, $A, $B, $DIF);

print "Enter output file name \n";
chomp ($output = <STDIN>);

chomp ($input = "in.txt");
open (IN, $input);
open (OUT, >"$output");

while (<IN>){
   ($ID, $A, $B) = split ("\t");
   #push @_, ($DIF = $B-$A);
   print OUT "$ID\t$A\t$B\t$DIF\n";

close (IN);
close (OUT);

I am stuck with trying to figure out how to code the calculation for the 4th column...
I tried using
push @_, ($DIF = $B-$A);
but it gives me the error that A and B is not numeric when it reads the header in the original file. Any help is appreciated!

5 Years
Discussion Span
Last Post by whoadiz

you can try testing $A and $B (not the best variable name choices, btw) for being numerical, try the guide here: How do I determine whether a scalar is a number/whole/integer/float?

Apart from that, there's no need to push to @_, in fact, it's probably a very bad idea. Assigning the result to $dif is enough.
While on the subject, it's recommended to use a three-argument 'open', and a local variable for the filehandles:

open (my $IN, '<', $input);
open (my $OUT, '>', $output);
Votes + Comments
Much good advice in this post.

I figured it out. Thanks, I just needed to check the value of A or B is a string or number like you said.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.