Re: Combine hash declaration/assignment into single statement?



"u" == usenet <usenet@xxxxxxxxxxxxxxx> writes:

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

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

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

not with that data in one statment. but there are many variations which
can be used.

first, you may already have the keys in an array for various reasons
(ordering, read from somewhere else, etc.). then you can use map to
assign integer values:

my @chars = ( 'a' .. 'z' ) ;
my %foo = map { $chars[$_ - 1] => $_ } 1 .. @chars ;

if you don't mind destroying @chars (say a copy is used) this works:

my %foo = map { shift @chars => $_ } 1 .. @chars ;

that can be used to merge two arrays if either one can be destroyed:

my %foo = map { shift @keys => $_ } @values ;
my %foo = map { $_ => shift @values } @keys ;

or if you just wanted the keys to exist (for checking if a string is in
a set):

my %foo = map { $_ => undef } @chars ;

uri

--
Uri Guttman ------ uri@xxxxxxxxxxxxxxx -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org
.



Relevant Pages