Saturday, 7 September 2013

I am unable to to understand following Perl code

I am unable to to understand following Perl code

I have the following Perl code.
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
my @array = ( 3, 4, 1, 4, 7, 7, 4, 1, 3, 8 );
my %unordered;
@unordered{@array} = undef;
foreach my $key (keys %unordered) {
print "Unordered: $key\n";
}
my %seen;
my @ordered;
foreach my $element (@array) {
if ( not $seen{$element}++ ) {
push @ordered, $element;
}
}
In the last foreach code block, I am unable to understand this - in the
first iteration, the expresssion not $seen{$element}++ evaluate to not 0 -
true - so the if block execute. In the second iteration the expression not
$seen{$element}++ should again evaluate to not 0 - true as the hash is
empty. So, reading the scalar $seen{$element} will read 0 and not 0 will
evaluate to true. So, the if block should execute again. But, the book
says it stops after first iteration. Can anyone explain this?

No comments:

Post a Comment