dsw
August 31, 2010, 5:44am
1
Hi,
In Perl, is it possible to use a range of numbers with '..' as a key in a hash?
Something in like:
%hash = (
'768..1536' => '1G',
'1537..2560' => '2G'
);
That is, the range operation is evaluated, and all members of the range are 'mapped' to the RHS value, so that for the first keypair, '1000' would return 1G.
I think somehow 'map' might be what i'm after, but can't find any reference material to support my theory.
Any advice welcome,
cheers
dsw
pludi
August 31, 2010, 6:39am
2
One way to construct this:
%hash = map { $a = '1G' if /768/ .. /1536/; $a = '2G' if /1537/ .. /2560/; $_ => $a }
768 .. 2560;
1 Like
Could I suggest a different approach?
perl -le'
$val = shift;
@ranges = (
[768, 1536, "1G"],
[1537, 2560, "2G"]
);
for (@ranges) {
print $_->[2] and last
if $_->[0] <= $val && $val <= $_->[1]
}
'
It produces:
% perl -le'
$val = shift;
@ranges = (
[768, 1536, "1G"],
[1537, 2560, "2G"]
);
for (@ranges) {
print $_->[2] and last
if $_->[0] <= $val && $val <= $_->[1]
}
' 1000
1G
% perl -le'
$val = shift;
@ranges = (
[768, 1536, "1G"],
[1537, 2560, "2G"]
);
for (@ranges) {
print $_->[2] and last
if $_->[0] <= $val && $val <= $_->[1]
}
' 2000
2G
1 Like
dsw
August 31, 2010, 7:03am
4
Awesome, thank you both pludi and radoulov - both very workable solutions.
cheers
dsw.