Hey,I am teaching myself to program in perl with a few online books. For the record, I am no longer in school so none of my questions are school assignments. I am just learning for fun.
Anyways, I have two questions.
First:
I am very confused by this code. I am testing a few of my ideas regarding how to complete the next exercise and I expected this to print "key = bbb value = bbat" at the end but instead it's printing "key = aaa value = aaapple." Can anybody explain to me why? Also, I know that I declared an uninitialized variable. When I understand this piece of the code I will put it to use. Thanks!
#!/usr/bin/perl -w
use strict;
my ($userin, $key, $value, %fred) ;
print "Type in a list of words. Type done when finished.\n" ;
%fred = ("aaa" =>"aaapple", "bbb" => "bbbat") ;
while (($key, $value) = each(%fred)) {
print "key = $key value = $value\n" ;
}
delete $fred{"aaapple"} ;
print "This is after the deleted aaaple" ;
while (($key, $value) = each(%fred)) {
print "key = $key value = $value\n" ;
}
Next:
I got a bit stuck on my latest perl exercize so I looked up the book's example in the hopes that I could understand it and create my own version. The program is supposed to ask users to enter words and then produce a hash such that the keys and values list which words were entered and how many times they were entered. My question is about line four. It seems as though the statement "$count{$word} = $count{$word} + 1;" translates into add one to the key $count associated with the value $word. I gues what confuses me is that I am used to the ++ statement looking like $count++ does $count{word}++ do the same thing for the key count?
chomp(@words = <STDIN>);
# read the words, minus newlines
foreach $word (@words) {
$count{$word} = $count{$word} + 1; # or $count{$word}++
}
foreach $word (keys %count) {
print "$word was seen $count{$word} times\n";
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.