Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Print out hash

by catfish1116 (Beadle)
on Feb 15, 2019 at 16:07 UTC ( [id://1229964]=perlquestion: print w/replies, xml ) Need Help??

catfish1116 has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to create a hash and then print it out. When executing program, I am getting $key & $value need explicit package. O wise monks, please show me the error of my ways :)

#! /usr/bin/perl use v5.12; use warnings; ## 2/15/19 my @people = qw{ fred barney fred wlima dino barney fred pebbles +}; my %count; # new empty hash $count{$_}++ foreach @people; while ( ($key, $value) = each %count) { print "$key => $value\n"; } ~

TIA the catfish

Replies are listed 'Best First'.
Re: Print out hash
by marto (Cardinal) on Feb 15, 2019 at 16:16 UTC

    Where you have:

    use v5.12;

    "Similarly, if the specified Perl version is greater than or equal to 5.12.0, strictures are enabled lexically as with use strict."(https://perldoc.pl/functions/use).

    So to fix your code, use my:

    while ( my ($key, $value) = each %count) {

    Returns:

    pebbles => 1 dino => 1 wlima => 1 fred => 3 barney => 2
Re: Print out hash
by pryrt (Abbot) on Feb 15, 2019 at 16:15 UTC

    The warnings that were printed are telling you what's wrong:

    Global symbol "$key" requires explicit package name (did you forget to + declare "my $key"?) at - line 11. Global symbol "$value" requires explicit package name (did you forget +to declare "my $value"?) at - line 11. Global symbol "$key" requires explicit package name (did you forget to + declare "my $key"?) at - line 12. Global symbol "$value" requires explicit package name (did you forget +to declare "my $value"?) at - line 12. Execution of - aborted due to compilation errors.

    You need to declare those two variables, which is easy enough to do with while ( my ($key, $value) = each %count) {

    showing the full code:

    #! /usr/bin/perl use v5.12; use warnings; ## 2/15/19 my @people = qw{ fred barney fred wlima dino barney fred pebbles +}; my %count; # new empty hash $count{$_}++ foreach @people; while ( my ($key, $value) = each %count) { print "$key => $value\n"; } __END__ __OUTPUT__ wlima => 1 barney => 2 dino => 1 fred => 3 pebbles => 1

    edit: the colon after the { looked like it was part of the code, started new paragraph instead.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1229964]
Approved by marto
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2024-04-23 10:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found