Shlomi Fish wrote:
On Saturday 16 Apr 2011 09:06:02 Gurunath Katagi wrote:
hi .. i am new to perl ..
i have a input file something pasted as below ..

16 50
16 30
16 23
17 88
17 99
18 89
18 1
..
--

and i want the output something like this :
16 50 30 23
17 88 99
18 99 1

i.e for each values in the first column, i want the elements in the second
column to be a one row ..

can be anybody give me psuedocode , to how to go about this ..
thank you

This should work (tested):

Regards,

        Shlomi Fish

----------------------------- SNIP ------------------------

#!/usr/bin/perl

use strict;
use warnings;

my $filename = shift(@ARGV);

open my $in_fh, '<', $filename
     or die "Cannot open '$filename' for reading";

You should include the $! or $^E variable in the error message so you know why it failed.


my $last_key = undef;

ICK!


my @values;

sub print_line
{

You are using a subroutine for this???   Really?

Why are you using global variables instead of lexically scoped variables? You should know better.


     print $last_key, ' ', join(' ', @values), "\n";

Or:

     print join( ' ', $last_key, @values ), "\n";

Or even:

     print "$last_key @values\n";

Is there really a good reason to make it more complicated than it needs to be?


     return;
}

while (my $line =<$in_fh>)
{
     chomp($line);

     my ($new_key, $new_value) = split(/\s+/, $line);

What if there is leading whitespace?

You do realize that split(/\s+/) removes ALL (trailing) whitespace so using chomp() is redundant.


     if ( ( !defined($last_key) ) or ($last_key eq $new_key))
     {
         push @values, $new_value;
     }
     else
     {
         print_line();
         @values = ($new_value);
     }


     $last_key = $new_key;
}

print_line();

close ($in_fh);



John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.                   -- Albert Einstein

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to