Your skill will accomplishwhat the force of many cannot PerlMonks

### Re^3: How to check if a variable's value is equal to a member of a list of values

by cls33 (Novice)
 on Mar 25, 2013 at 15:24 UTC ( #1025324=note: print w/replies, xml ) Need Help??

Seems like I'm on the right track, but this is a more elegant implementation. I was not previously familiar with the ability to suck an entire array into a hash using the @hash{@array}=() syntax.

One quick syntactical question... using this method, how would I set each hash key to a defined static value? Using something like:

@hash{@array}='MyValue';

Only seems to set the value for the first key...
• Comment on Re^3: How to check if a variable's value is equal to a member of a list of values

Replies are listed 'Best First'.
Re^4: How to check if a variable's value is equal to a member of a list of values
by LanX (Bishop) on Mar 25, 2013 at 15:36 UTC
> I was not previously familiar with the ability to suck an entire array into a hash

it's called "hash slice"! see perldata#Slices

> using this method, how would I set each hash key to a defined static value?

assign a list of same length

DB<156> @array=1..5 => (1, 2, 3, 4, 5) DB<157> @hash{@array} = ('my val') x @array => ("my val", "my val", "my val", "my val", "my val") DB<158> \%hash => { 1 => "my val", 2 => "my val", 3 => "my val", 4 => "my val", 5 => + "my val" }

Cheers Rolf

( addicted to the Perl Programming Language)

#### UPDATE

for completeness TIMTOWTDI:

\$hash{\$_}="my val" for @array

has less of a memory footprint.

and

my %hash = map { \$_ => "my val" } @array;

is DRYer and makes sure the whole hash is reinitiated.

Re^4: How to check if a variable's value is equal to a member of a list of values
by choroba (Bishop) on Mar 25, 2013 at 15:37 UTC
You have to provide a list of values on the right hand side. For example, you can try:
@hash1{@array} = ('value') x @array; @hash2{@array} = 0 .. \$#array;
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Hm... makes sense. But how do I handle it if I don't know the size/length of the array? Do I really have to check that and then programmatically build an array in a loop? Or is there a syntactical shortcut?
I do not understand. In my examples, the size of the array is not hardcoded, it is dynamically computed from @array in the scalar context or \$@array.
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Create A New User
Node Status?
node history
Node Type: note [id://1025324]
help
Chatterbox?
 erix chuckles [choroba]: linenlessnesses

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (9)
As of 2017-10-17 15:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My fridge is mostly full of:

Results (233 votes). Check out past polls.

Notices?