Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

a reoccurring problem for novice in perl

Status
Not open for further replies.

szzxy

Technical User
Aug 14, 2010
8
CA
Hi experts,
I have an input file with 2 columns (col_1 and col_2). The information in col_1 can occur more than once throughout the file, whereas the info on column 2 are all unique.
I tried to write a perl program to put all col2 info into one row when the col1 are the same.

...
##I have parsed my file
my $initial=0;
while(my $line=<file>){
if ($col_1 eq $initial ){
push(@table, $col_2);
$initial=$col_1;
} else {

}
}

What should I write in else? so that I can make another row for the $col_2 if the col_1 is different from the previous one?

Regards,
szsy




}
}
 
Hi,

It would be best to use a hash structure, storing values in an array context:

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

my %hash = ();

while (my $line = <DATA>) {
	my ($name, $score) = split /\,\s/, $line; 
	push (@{$hash{$name}}, $score);
}

print "$_, ", join (', ', @{$hash{$_}}), "\n" foreach (keys %hash);


__DATA__
Chris, 6
Peter, 10
William, 14
Peter, 17
Lucy, 18
Peter, 19
Hayley, 20
Lucy, 40

Chris
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top