Hi monks, I am studying the references on perlreftul. It showed an example of using references to a hash containing countries and cities(http://perldoc.perl.org/perlreftut.html). I created a test file containing the country city list,
Chicago, USA Frankfurt, Germany Berlin, Germany Washington, USA Helsinki, Finland New York, USA
then test the code as below:
#!/usr/bin/perl -w use strict; my %table; while (<>){ chomp; my ($city,$country)=split/,/; $table{$country}=[] unless exists $table{$country}; push @{$table{$country}}, $city; } my $a=$table{"USA"}; print $a; #line 12 foreach my $country (sort keys %table){ if ($country eq "USA"){ print "USA is found\n"; } else{} }
Wierd thing happend. first, I can not print the element of $table{"USA"}, giving the error "Use of uninitialized value in print at country_city.pl line 12, <> line 6.". Second, the foreach loop can not find $country equals to "USA", thus, it can not print "USA is found", it just printed nothing. What happened? This really confused me. Thanks.

In reply to Can not print hash element by lightoverhead

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.