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:

#!/usr/bin/perl
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>){
   chomp;
   ($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!

Recommended Answers

All 2 Replies

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);
commented: Much good advice in this post. +8

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.