Re: Combine hash declaration/assignment into single statement?



(usenet@xxxxxxxxxxxxxxx uttered:)
It is often possible to declare and assign a variable in a single
statement, such as:
my $foo = 'bar';
or
my @foo = qw{bar baz};

Is it possible to do this in a single statement (under strict):

my %character_value;
@character_value{'a'..'z'} = (1..26);

My first thought was to do this:

#!/usr/bin/perl

use warnings;
use strict;
use List::MoreUtils qw(zip);

my %character_value = zip('a'..'z', 1..26);

But as it turns out, there is a subtle distinction between lists and
arrays of which I was not previously aware, and List::MoreUtils::zip
needs arrays:

Type of arg 1 to List::MoreUtils::mesh must be array (not null
operation) at foo.pl line 14, near "26)"
Type of arg 2 to List::MoreUtils::mesh must be array (not null
operation) at foo.pl line 14, near "26)"


It's not a single statement, but (in addition to any of Uri's
excellent suggestions) you can still do this:

#!/usr/bin/perl

use warnings;
use strict;
use List::MoreUtils qw(zip);

my @keys = 'a'..'z';
my @values = 1..26;

my %character_value = zip(@keys, @values);




Rick
--
key CF8F8A75 / print C5C1 F87D 5056 D2C0 D5CE D58F 970F 04D1 CF8F 8A75
Aren't your machines getting faster much more quickly than your
programmers are getting smarter?
:Peter Coffee
.



Relevant Pages