From:                   Marco Pacini <i...@marcopacini.org>
Subject:                Assignment Operator
Date sent:              Thu, 26 Nov 2009 12:31:54 +0100
To:                     beginners@perl.org

> Hi All,
> 
> I'm studying Perl since one week on "Learning Perl" written by L. Wall
> and in the paragraph "Assignment Operators" i don't understand why
> this: 
> 
>       ($temp = $global) += $constant;
> 
> is equivalent of:
> 
>       $tmp = $global + $constant;

I believe you meant $temp, not $tmp
> 
> Instead,  before i read it, i thought it was equivalent of:
>       
>       $temp = $global;
>       $temp = $temp + $constant;

You were right, though unless the $temp is a tie()d variable, they 
are all equivalent.

If $temp is tie()d, then the first and third will call the STORE 
method twice abd FETCH once, while the second calls just STORE once.

This may cause the result to be different if the STORE modifies the 
stored value. Eg. by rounding it.


#!perl
package TstTie;
require Tie::Scalar;

@ISA = qw(Tie::Scalar);

sub FETCH { print "FETCH ${$_[0]}\n"; return ${$_[0]} }
sub STORE { print "STORE $_[1]\n"; ${$_[0]} = $_[1] }
sub TIESCALAR { my ($class, $value) = @_; return bless( \$value, 
$class)}

package main;

my $temp=4;
tie $temp, 'TstTie', 4;

my $global = 10;
my $constant = 7;

print "Original:\n";
($temp = $global) += $constant;
print "Result: $temp\n\n";

print "First:\n";
$temp = $global + $constant;
print "Result: $temp\n\n";

print "Second:\n";
$temp = $global;
$temp = $temp + $constant;
print "Result: $temp\n\n";
__END__


(Keep in mind that the 
  print "Result: $temp\n\n";
causes on more FETCH!

Jenda
===== je...@krynicky.cz === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
        -- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to