954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Parsing & Calculating

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!

whoadiz
Newbie Poster
15 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

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);
erezschatz
Newbie Poster
18 posts since Jan 2011
Reputation Points: 26
Solved Threads: 4
 

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

whoadiz
Newbie Poster
15 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You