This works.

#!/usr/bin/perl
use strict;
use warnings;

my %hash=();
while(<>){
        chomp(my $line=$_);
        my($col1, $col2)=split(/\s+/, $line);
        push(@{ $hash{$col1} }, $col2);
}

for my $key (sort keys %hash){
        print "$key";
        for (@{ $hash{$key} }){
                print " $_";
        }
        print "\n";
}


--- On Sat, 4/16/11, Shlomi Fish <shlo...@iglu.org.il> wrote:

> From: Shlomi Fish <shlo...@iglu.org.il>
> Subject: Re: help in scripting
> To: beginners@perl.org
> Cc: "Gurunath Katagi" <gurunath.kat...@gmail.com>
> Date: Saturday, April 16, 2011, 2:41 AM
> 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";
> 
> my $last_key = undef;
> my @values;
> 
> sub print_line
> {
>     print $last_key, ' ', join(' ', @values),
> "\n";
> 
>     return;
> }
> 
> while (my $line = <$in_fh>)
> {
>     chomp($line);
> 
>     my ($new_key, $new_value) = split(/\s+/,
> $line);
>     
>     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);
> 
> 
> -- 
> -----------------------------------------------------------------
> Shlomi Fish       http://www.shlomifish.org/
> My Favourite FOSS - http://www.shlomifish.org/open-source/favourite/
> 
> "We're not doing it for money… we're doing it for a
> shitload of money!"
>     -- Spaceballs, http://www.imdb.com/title/tt0094012/
> 
> Please reply to list if it's a mailing list post - http://shlom.in/reply .
> 
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
> 
> 
>

--
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