efficasy has asked for the wisdom of the Perl Monks concerning the following question:

Hi, If Gurus can help me a small problem I am facing.. I have file, with a structure like below, Student Id Class John 23 2 Mark 33 3 Jerry 44 2 Sam 55 2 Tom 65 3 I want to print out a output like below, can you please help me how? Class 2 = John,Jerry, Sam Class 3 = Mark, Tom

Replies are listed 'Best First'.
Re: Data Structure
by NetWallah (Canon) on Jul 20, 2016 at 22:51 UTC
    This smells like homework, so you can use this working solution if you can explain or re-write it.
    echo "Student Id Class John 23 2 Mark 33 3 Jerry 44 2 Sam 55 2 Tom 65 3 " | perl -ane '$F[2]=~/^\d+$/ or next;push @{$h[$F[2]]},$F[0]}{ $h[$_] + && print qq|Class $_ = |,join(",",@{$h[$_]}),qq|\n| for 0..$#h'
    Output:
    Class 2 = John,Jerry,Sam Class 3 = Mark,Tom
    UPDATE: FWIW, the Data structure used in the code above is an "Array of Array(ref)s".
    The code posted below this node uses a Hash of array refs.

            "Software interprets lawyers as damage, and routes around them" - Larry Wall

Re: Data Structure
by Anonymous Monk on Jul 20, 2016 at 21:30 UTC

    You will need to group your input by the specified criteria, so that the related elements are readily accessible at the print time. Now, what are the ways to group data? To sort it would be one, but, judging by the structured and relational nature of your data, the most appropriate approach seems to be to index it as if a database.

    Now, what is the perl construct for handling arbitrarily indexed data mapping? What type of variable would you use to store the structure?

    Try to answer the above question; we can then advise you further. The perldsc may also be worth consulting.

Re: Data Structure
by Anonymous Monk on Jul 21, 2016 at 02:13 UTC
    Something like this:
    my $data = <<EOD; Student Id Class John 23 2 Mark 33 3 Jerry 44 2 Sam 55 2 Tom 65 3 Test +stud 28 2 EOD my %h; my @arr = split /\s+/, $data ; for (my $c=3; $c<($#arr);$c+=3) { push @{$h{$arr[$c+2]}}, $arr[$c]; } print $_."=".join(",",@{$h{$_}})."\n" for (keys %h);
    Output:
    3=Mark,Tom 2=John,Jerry,Sam,Teststud