Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: 2 newby questions

by Athanasius (Monsignor)
on Jun 14, 2012 at 04:44 UTC ( #976113=note: print w/ replies, xml ) Need Help??


in reply to Re: 2 newby questions
in thread 2 newby questions

"Why not try it?"

Excellent advice, especially with the caveats given.

PS: the answer is "no."

Some clarification may help the OP:

There are 4 ways to increment a counter by 1:

(A) $count{$word} = $count{$word} + 1; (B) $count{$word} += 1; (C) $count{$word}++; (D) ++$count{$word};

First, note that the $ prefix is required in $word here (this was supplied in the OP’s code, but not in the OP’s question). The difference between (C) and (D) is detailed in perldoc.

The real difference arises when warnings are turned on. (A) produces warnings of the form:

Use of uninitialized value within %count in addition (+) at ... line ..., <STDIN> line 1.

whereas (B), (C), and (D) do not. In all 4 cases, Perl creates the hash entry by a process called autovivification (on which there is a useful tutorial by Uri Guttman), which creates a new hash entry with the specified key and assigns it a value of undef. The difference is that in (A), Perl initially sees you accessing this undefined hash entry in the addition on the right of the assignment and issues a warning, whereas in (B), (C), and (D), Perl is smart enough to know that the warning is not needed. But in their effects, (A), (B), (C), and (D) are the same, in that each increments by 1 the value of the %count entry which has $word as its key.

Update: SuicideJunkie (below) makes an interesting point. A good place to follow-up on it is in the thread begun by First JAPH - Spell perl in two hundred and eighty five thousand and seventy four easy steps, a 10-year-old post which turns up from time to time in Selected Best Nodes.

HTH,

Athanasius <°(((><contra mundum


Comment on Re^2: 2 newby questions
Select or Download Code
Re^3: 2 newby questions
by SuicideJunkie (Priest) on Jun 14, 2012 at 13:47 UTC

    The effects do vary in some cases, since ++ is smarter than it looks.

    use strict; use warnings; my $index = 'AH'; $index++; print "++ gives $index\n"; $index += 1; print "+= gives $index\n";

    Results in:

    ++ gives AI Argument "AI" isn't numeric in addition (+) at test.pl line 7. += gives 1

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://976113]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (8)
As of 2014-08-21 02:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (127 votes), past polls