http://qs321.pair.com?node_id=1137539

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

Hi experts, I have an array of hash like below.
Input:

$VAR1=[
{
case=>'case1',
id =>'001',
name => 'raja',
degree => 'bcom'
},
{
case=>'case1',
id =>'002',
name => 'raja1',
degree => 'bcom'
},
{
case=>'case2',
id =>'003',
name => 'bala',
degree => 'bcom'
},
{
case=>'case2',
id =>'004',
name => 'gopi',
degree => 'bcom'
}
]
i want the output should be like below. The same order need to be maintain. will any one help me to solve this ?

Need output like below: Case1:
001) raja, bcom,
002) raja1, bcom
Case2:
003) Bala,bcom
004) gopo, bcom


Thanks in advance
  • Comment on convert array of hash into formatted one

Replies are listed 'Best First'.
Re: convert array of hash into formatted one
by choroba (Cardinal) on Aug 05, 2015 at 17:00 UTC
    Just iterate over the array with for, use the dereference operator -> to access the inner hash'es values.
    #!/usr/bin/perl use warnings; use strict; my @arr = ( { case => 'case1', id => '001', name => 'raja', degree => 'bcom' }, # ... ); my $case = q(); for my $hash (@arr) { if ($hash->{case} ne $case) { print ucfirst $hash->{case}, ":\n"; $case = $hash->{case}; } print "$hash->{id}) $hash->{name}, $hash->{degree}\n"; }

    You have to be sure that the cases are continuous in the data structure. If they aren't, you'll have to sort the array.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Hi All,
      Thanks all for your prompt response. Now i got an idea how to do this.
      Thanks again.
Re: convert array of hash into formatted one
by toolic (Bishop) on Aug 05, 2015 at 16:53 UTC
Re: convert array of hash into formatted one
by anonymized user 468275 (Curate) on Aug 05, 2015 at 17:14 UTC
    Looks like you need a sort function or block and to keep the previous (sorted) case in an up-scope variable, e.g.
    my $prevCase = ''; for my $i (sort caseThenId (0..$#$var1) { my $case = $var1->[$i]{case}; print "$case:"\n" if $case ne $prevCase; $prevCase = $case; print $var1->[$i]{id} . ") " . $var1->[$i]{name} . ", " . $var1->[$i]{degree} . "\n"; } sub caseThenId { $var1->[$a]{case} cmp $var1->[$b]{case} or $var1->[$a]{id} cmp $var1->[$b]{id}; }
    Update: $var1 should be a reference to your array in the above example.

    One world, one people

      Why would you need a sort? It appears the array is already in the order the OP wants.

      -derby
        Two reasons: 1, the OP did not specify what sorting had been applied. 2, the four records shown might be accidentally in order, or the example might not fit the actual data when applied, so it might help the OP to see what the sort algorithm should be.

        One world, one people