Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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!

In reply to Re: using hash to compare with string and print the string by thanos1983
in thread using hash to compare with string and print the string by Newbie95

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-24 20:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found