On Fri, Feb 10, 2012 at 12:32 PM, zilore mumba <zmu...@yahoo.com> wrote: > Please help with some very simple code below which somehow I a, not getting > right. > I have strings consisting of $day, $month, $year, $hour, $min, followed by > some float values which I call @rain, as in the attached file 'text1.txt'. > I want rewrite this data as $year, $month, $day, $hour, $min, @rainin as > in 'text2.txt', but with the date also formatted to have one space between > each field > Help will be appreciated. > Zilore > > > #!/usr/bin/perl -w > use strict; > > use warnings; > > open (IN, "< text1") or die "open 'text1' failed: $!\n"; > open (OUT, ">$text2") or die "open 'text1' failed: $!\n"; > > # Copy first 3 lines unchanged. > print OUT scalar(<IN>) for 1..3; > > # Reformat the numbers on each remaining line. > > while (<IN>) > { > my ($month,$day,$year,$hour,$min,@rain) = split; > > # printf ("%04d%02d%02d%02d%02d\n",$year,$month,$day,$hour,$min); > $_ = sprintf "%5.1f", $_ foreach @rain; > > print OUT ($year,$month,$day,$hour,$min, join(" ", @rain), "\n"); > } > > # Close files > close IN or die "close IN: $!\n"; > close OUT or die "close OUT failed: $!\n"; > } >
Here is are some examples using your code as a starting point. HTH, Ken use strict; use warnings; # Reformat the numbers on each remaining line. my $test = shift || 1; while (my $line = <DATA>) { my ($month,$day,$year,$hour,$min,@rain) = split(" ",$line); @rain = map { sprintf"%5.1f", $_ } @rain; if ($test == 1) { # You had the following line commented out. # Just add spaces to this line. # printf ("%04d%02d%02d%02d%02d\n",$year,$month,$day,$hour,$min); printf "%04d %02d %02d %02d %02d",$year,$month,$day,$hour,$min; printf " $_", $_ foreach @rain; print "\n"; } elsif ($test == 2) { # Changing your print statement to join all variables, # sparatated by a space. # print ($year,$month,$day,$hour,$min, join(" ", @rain), "\n"); print join(" ",$year,$month,$day,$hour,$min, @rain), "\n"; } } __DATA__ 12 29 2011 10 55 1.5 2.5 12.5 2 14 2012 14 30 3.5 4.5 13.5 _______________________________________________ ActivePerl mailing list ActivePerl@listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs