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

I have following code which goes on for 48 hash, is there any way I can use some kind of loop and shorten the code instead of doing the process again and again??
Every sortedHash(%finalMap1); will return different data which are to be stored in different arrays.
@returned_sorted1 = sortedHash(%finalMap1); @percentile_index1 = percentile(@returned_sorted1); @returned_sorted2 = sortedHash(%finalMap2); @percentile_index2 = percentile(@returned_sorted2); @returned_sorted3 = sortedHash(%finalMap3); @percentile_index3 = percentile(@returned_sorted3);

Replies are listed 'Best First'.
Re: How to shorten this particular code
by Fletch (Bishop) on Apr 28, 2008 at 04:00 UTC

    Having a series of variables named sequentially (%finalMap1, %finalMap2, etc.) is a sure sign you really wanted them all contained in another data structure (in the %finalMap... case possibly an Array of Hashrefs (AoH), for example; similarly for the others an AoA might be called for). See the documentation such as the data structures cookbook or perllol after reading the references tutorial.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: How to shorten this particular code
by kyle (Abbot) on Apr 28, 2008 at 03:57 UTC
    my @array_of_hashes = \( %finalMap1, %finalMap2, ... ); foreach my $finalMap_ref ( @array_of_hashes ) { push @returned_sorted, [ sortedHash( %{$finalMap_ref} ) ]; push @percentile_index, [ percentile( @{$returned_sorted[-1]} ) ]; }

    At that point, @{ $returned_sorted[ 2 ] } is what would have been @returned_sorted3 in your version. If you store your various %finalMap hashes in an array of hashes to begin with, you can avoid having them all listed out in the initial assignment. If you don't really need to keep the values of @returned_sorted, you can replace the loop's innards with this:

    push @percentile_index, [ percentile( sortedHash( %{$finalMap_ref} ) ) ];

    Since you're not doing this already, I'm guessing you're not familiar with references. If that's true, have a look at perlreftut and perlref. After that, maybe References quick reference.

      Yes, you are right. Thanks a lot for guiding me.
Re: How to shorten this particular code
by GrandFather (Saint) on Apr 28, 2008 at 03:59 UTC

    Looks to me like you need a major rethink of your data structure. I'd be heading for something like:

    my @data; for my $itemIndex (0 .. 47) { $data[$itemIndex]{finalMap} = GetTheData ($itemIndex + 1); $data[$itemIndex]{sorted} = sortedHash ($data[$itemIndex]{finalMap +}); $data[$itemIndex]{percentile} = sortedHash ($data[$itemIndex]{sort +ed}); }

    but without a whole lot more context it's very hard to give good advice.

    The important point is that whenever you start down the path of "$id1, $id2, $id3" you should really be thinking in terms of an array: "$id[0], $id[1], $id[2]"


    Perl is environmentally friendly - it saves trees