in reply to Re: Array in a Hash
in thread Array in a Hash

Hello,
Thank you for your reply. For simplicity sake, at any one given time there can be 21 fruit baskets. Each basket will contain X number of fruit consisting of "Fruit Names". So I was trying to use the hash of 0-20, for a total of 21, ( ex. $fruit{0}=248 to identify the total number of pieces of fruit in the basket, and then use ex. $fruit{0}{'fruits'}, to contain an array of the types of fruit that make up the value of $fruit{0}.

I see you change "There are $fruit{0} ... "to There are ", scalar @{ $fruits{0}{fruit} }, ", but I actually was wanting to use $fruit{0} to list the total pieces of fruit in the basket. So in this example, Basket 1 contain 248 pieces of fruit consisting of Apples, Pears, Bananas, Peaches, and Grapes

Thanks
Gary

Replies are listed 'Best First'.
Re^3: Array in a Hash
by NetWallah (Canon) on Sep 04, 2009 at 05:32 UTC
    Here is some code that is structured based on your description.

    Coding this way does require some knowledge of perl references. Hopefully, this will show you their power and relative simplicity.

    #!/usr/bin/perl use strict; use warnings; my @basket = ( #Left bracket indicates start of a list ... (Array of h +ash-refs) # Populate Zero'th basket as a hash-ref: { count=> 254, # Expecting this many fruit here fruit=> [ qw( Apple pear Banana Peach ) ], type => "All Season" }, # End of Zero'th basket {} # First (Empty) basket is created (This is not necessary) ); # End of all baskets # Adding "Grapes" to zero'th basket ... my $fruit_ref = $basket[0]{fruit} ; push @$fruit_ref, "Grapes"; $basket[0]{count}++; # Increment how many fruit # Populate First basket with tropical fruit: $basket[1]{fruit} = [ qw|papaya guava mango| ]; $basket[1]{count} = scalar ( @{ $basket[1]{fruit} }); # Auto count $basket[1]{type} = "Tropical"; # Print fruit info.. print "Basket# Type \t\tCount \tContents -------\n"; my $basket_nbr = 0; for my $b (@basket){ $basket_nbr++; #For printing, basket numbers start with 1 print "$basket_nbr \t$b->{type} \t$b->{count} \t@{$b->{fruit} }\n +"; }
    Output:
    Basket# Type Count Contents ------- 1 All Season 255 Apple pear Banana Peach Grapes 2 Tropical 3 papaya guava mango

         Potentia vobiscum ! (Si hoc legere scis nimium eruditionis habes)