Reputation: 66
This is the whole script, that for some mysterious to me reason outputs "642"
#!usr/bin/perl
%vvv = (1,2,3,4,5,6);
$#vvv--;
%vvv = reverse %vvv;
print keys %vvv, "\n";
Also what does "keys" in the last statement do? Thanks for your time. I am just on hurry I don't have proper time to do my research. So again I appreciate you input.
Upvotes: 3
Views: 214
Reputation: 67900
You should always run scripts with
use strict;
use warnings;
If you had, you would have noticed an error:
Global symbol "@vvv" requires explicit package name at ...
Which means that $#vvv
refers to the maximum index of the array @vvv
, not the hash. In perl, @vvv
and %vvv
are two separate variables. So @vvv
has nothing to do with %vvv
, and that operation is without any use.
What the person who wrote the code might have been thinking of is a way to truncate an array:
my @array = 1 .. 6; # 1,2,3,4,5,6 but written as a range
$#array--; # lower maximum index by 1
print "@array"; # prints "1 2 3 4 5"
However, that does not work wish hashes.
And as Friar has explained, reverse
is a way to swap hash keys and values around. When used on a string, it reverses the string, e.g. "foobar" -> "raboof", but when used on a list, it reverses it, so 1,2,3,4,5,6
becomes 6,5,4,3,2,1
.
Upvotes: 20
Reputation: 84
$#vvv-- looks like a comment. What's happening is the hash, being an even numbered element array, is just being reverse. So it goes from:
%vvv = (
1 => 2,
3 => 4,
5 => 6
);
to:
%vvv = (
6 => 5,
4 => 3,
2 => 1
);
So when the keys are printed, it grabs 642, or the new, current keys of the hash.
Upvotes: 6