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!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|