Results 1 to 3 of 3

Thread: Reading columns

  1. #1
    Join Date
    Jul 2003
    Posts
    34

    Unanswered: Reading columns

    Hi,
    I have a file with the following data:
    a:1:m
    b:2:n
    c:1:h
    d:2:k
    f:2:r

    I want the output to be based on the matching of the second column:

    1
    m,h

    2
    n,k,r

    I am trying this way, but not getting there:
    #!/usr/bin/perl
    my @second;
    $file="a.txt";
    open (DAT, $file) || die ("Could not open file $file");
    $i=0;
    for $line (<DAT>) {
    my ($a,$b,$c)=split(/:/,$line);
    chomp $c;
    push (@ram, "$c");
    %ba = ("$b", @second);
    }
    while (($key,$value) = each (%ba)) {
    print $key.",".$value;
    print $key;
    }
    print %ba;


    Any help will be greatly appreciated

  2. #2
    Join Date
    Feb 2006
    Posts
    56
    one way using a hash of arrays:

    Code:
    use strict;
    use warnings;
    my $file="a.txt";
    my %hash = ();
    open (DAT, $file) || die ("Could not open file $file");
    while (my $line = <DAT>) {
       chomp($line);
       my ($v1,$v2) = (split(/:/,$line))[1,2];
       push @{$hash{$v1}},$v2;
    }
    close(DAT);
    foreach my $key (sort {$a <=> $b} keys %hash) {
       print "$key\n",join(',',@{$hash{$key}}),"\n\n";
    }

  3. #3
    Join Date
    Jul 2003
    Posts
    34
    This worked. Thanks much! Great Help!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •