On Mon, Dec 22, 2008 at 06:49, RP <rpg.jha...@gmail.com> wrote:
> I am new to perl having basic idea about the programming and scripting
> language, so I am learning Perl through Perl Cookbook, 2nd edition.
>
> on page 118, (receipe 4.4 Implementing Sparse Array), Here is one
> statement.
>
> Using a hash representation, you should instead do either this to
> process elements in index order:
>
> foreach $element ( @fake_array{ sort {$a <=> $b} keys %fake_array } )
> {
>    # do something with $element
> }
>
> Question: I am not able to understand the statement -"@fake_array
> { sort {$a <=> $b} keys %fake_array }".
> I understood that we are sorting the keys of a hash %fake_array. But
> what is the meaning of @fake_array here???
>
> Appreciate your help to explain me this.
snip

You are looking at too little of the code.  The variable is
@fake_array{} which means that it is a hash slice* of %fake_array.
Slices are ways of asking for more than one item from a hash or an
array at a time.

if you have

my %hash = ( a => 1, b => 2, c => 3 );

then

my @list = @hash{"a", "b", "c"};

is the same as

my @list = ($hash{a}, $hash{b}, $hash{c});

A sparse array is one where that looks like an array, but does not
store empty values.  So, given the indexes 1, 1000, and 10000 an array
would store 10001 elements with 3 having a value and the rest being
undefinded, but a sparse array would only store 3 elements.  Because
hashes are unordered, to get the behavior of an array in a for loop
(index 0, followed by index 1, etc.) you must sort the keys to fetch
the values in index order.  So

sort {$a <=> $b} keys %fake_array

is sorting the keys.  The @fake_array{} is then a hash slice on those
sorted keys.  You could also implement the code like this


for my $key (sort {$a <=> $b} keys %fake_array) {
   my $element = $fake_array{$key};
   # do something with $element
}

* http://perldoc.perl.org/perldata.html#Slices

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to