[...]
Hi Vineet
You could format *pretty* by using sprintf() instead of print. I would do
it like below.
use strict;
use warnings;
my $mdout_file = "mdout.txt";
my $mdout_xtemp_file = "temp.txt";
open IN, $mdout_file or die;
open OUT, ">$mdout_xtemp_file" or die;
while (<IN>){
if (/TEMP/) {
my $time = (substr($_, 30, 14));
$time =~ s/\s//g;
my $temp = (substr($_, 53, 10));
$temp =~ s/\s//g;
print OUT sprintf("%4.1f %6.2f\n", $time*2, $temp);
}
}
The solution above *assumes* that you would know beforehand the widths you
want for each column (determined by the largest number in each column you
want to format).
The solution below allows you to determine the greatest width required
programmatically using the max() function from the List::Util module. Then,
the max widths for each column are used in the sprintf function, (which uses
a '*' as a placeholder, if thats an accurate term for the asterisk :-) ).
This would provide a better solution (in place of 'hard coding' the widths
in sprintf).
#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw/ max /;
my $mdout_file = "mdout.txt";
my $mdout_xtemp_file = "temp.txt";
open IN, $mdout_file or die;
my @time;
my @temp;
while (<IN>){
if (/TEMP/) {
my $time = (substr($_, 30, 14));
$time =~ s/\s//g;
my $temp = (substr($_, 53, 10));
$temp =~ s/\s//g;
push @time, $time*2;
push @temp, $temp;
}
}
close IN or die $!;
my $maxlen_time = max map{ length } @time;
my $maxlen_temp = max map{ length } @temp;
open OUT, ">$mdout_xtemp_file" or die;
for my $i (0..$#time) {
print OUT sprintf("%*.1f %*.2f\n",
$maxlen_time, $time[$i], $maxlen_temp, $temp[$i]);
}
close OUT or die $!;
Chris
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>