making arrays from tab-delimited text file column
Posted
by
absolutenewbie
on Stack Overflow
See other posts from Stack Overflow
or by absolutenewbie
Published on 2012-04-14T14:40:20Z
Indexed on
2012/04/14
23:29 UTC
Read the original article
Hit count: 375
I was wondering if anyone could help a desperate newbie with perl with the following question. I've been trying all day but with my perl book at work, I can't seem to anything relevant in google...or maybe am genuinely stupid with this.
I have a file that looks something like the following:
Bob April
Bob April
Bob March
Mary August
Robin December
Robin April
The output file I'm after is:
Bob April April March
Mary August
Robin December April
So that it lists each month in the order that it appears for each person.
I tried making it into a hash but of course it wouldn't let me have duplicates so I thought I would like to have arrays for each name (in this example, Bob, Mary and Robin). I'm afraid to upload the code I've been trying to tweak because I know it'll be horribly wrong. I think I need to define(?) the array. Would this be correct?
Any help would be greatly appreciated and I promise I will be studying more about perl in the meantime.
Thank you for your time, patience and help.
#!/usr/bin/perl -w
while (<>) {
chomp;
if (defined $old_name) {
$name=$1;
$month=$2;
if ($name eq $old_name) {
$array{$month}++;
}
else {
print "$old_name";
foreach (@array) {
push (@array, $month);
print "\t@array";
}
print "\n";
@array=();
$array{$month}++;
}
}
else {
$name=$1;
$month=$2;
$array{month}++;
}
$old_name=$name;
}
print "$old_name";
foreach (@array) {
push (@array, $month);
print "\t@array";
}
print "\n";
© Stack Overflow or respective owner