in reply to using hash to compare with string and print the string
Hello Newbie95,
Just a minor note here because you said you are doing your first steps on hashes.
I noticed that you have an array of keys and a hash below. If the hash is not manually defined you can use hash slicing and assign the keys and values in one step to avoid typing everything manually. For example see below:
my @keys = qw(b d a c); my @values = qw(200 100 30 40); my %hash; @hash{@keys} = @values; print Dumper \%hash;
Then simply as fellow Monks demonstrate to you, iterate over the keys and if the key exists print.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @keys = qw(b d a c); my @values = qw(200 100 30 40); my %hash; @hash{@keys} = @values; print Dumper \%hash; foreach my $key (@keys) { if (exists $hash{$key} ) { print "array element: $key = $hash{$key} inside \%hash\n"; } next; } __END__ $ perl test.pl $VAR1 = { 'a' => '30', 'c' => '40', 'b' => '200', 'd' => '100' }; array element: b = 200 inside %hash array element: d = 100 inside %hash array element: a = 30 inside %hash array element: c = 40 inside %hash
Here is the documentation regarding perldata/Slices. In case you want to read a bit more on how to play with them :).
BR / Thanos
Seeking for Perl wisdom...on the process of learning...not there...yet!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: using hash to compare with string and print the string
by WoodyWeaver (Monk) on May 16, 2019 at 13:38 UTC |
In Section
Seekers of Perl Wisdom