Home > Archive > PERL Beginners > August 2006 > Re: .= command in perl
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Re: .= command in perl
|
|
| Paul Lalli 2006-08-24, 6:57 pm |
| knp.2573139@gmail.com wrote:
> $check .= "_check";
> $check = "_check";
>
> what is the differnce b/w the above two commands.
Assuming $check is previously undefined, nothing.
However, try this:
my $foo = 'start';
$foo = 'end';
my $bar = 'start';
$bar .= 'end';
print "Foo: $foo, Bar: $bar\n";
FYI, all Perl operators are documented in:
perldoc perlop
Paul Lalli
| |
| Uri Guttman 2006-08-25, 6:57 pm |
| >>>>> "PL" == Paul Lalli <mritty@gmail.com> writes:
PL> DJ Stunks wrote:[color=darkred]
PL> Pretty sure that's by design, to allow you to write things like:
PL> my $data;
PL> while ($chunk = get_data()) {
PL> $data .= $chunk;
PL> }
PL> without having to say `my $data = '';`
PL> The same thing happens for the += operator and dealing with numbers as
PL> well.
yes, the left side of .= and += are immune to uninitialized
warnings. this is true for -=, ++ and -- as well.
perl -lwe '$x += 1; print $x'
1
perl -lwe '$x++; print $x'
1
perl -lwe '++$x; print $x'
1
perl -lwe '--$x; print $x'
-1
perl -lwe '$x -= 1; print $x'
-1
and it is only quiet for those ops which modify in place:
perl -lwe '$x = $x + 1; print $x'
Use of uninitialized value in addition (+) at -e line 1.
1
note that this doesn't work for *= and probably all/most of the other x=
ops
perl -lwe '$x *= 1; print $x'
Use of uninitialized value in multiplication (*) at -e line 1.
0
it is a form of autovivification. with simple scalars like this it
doesn't save too much, just a simple assignment and even less if you
declare it with my. but in a data structure where you may add/subtract
or append a value to a member, it is very nice. you don't always know if
you have initialized something and you don't want to have to do it to
every member in advance which would get very ugly quickly. so this idiom
is meant to work as the above:
$obj->{buffer} .= $more_text ;
$obj->{counter}++
i have seen bad code that autovivified refs that was so horrible to
read (note that this is done EACH time something was done to a member!) :
$obj->{foo} = {} unless $obj->{foo} ;
$obj->{foo}{bar} = $baz ;
usually that was a full if block as well. so this autoviv (in both ref
and scalar form) saves us from this hell of checking before any possible
first time use in a structure. and since those first time uses could be
in many places in complex code it is a major win to keep warnings quiet
when you modify a member in place in one of those ways.
uri
--
Uri Guttman ------ uri@stemsystems.com -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org
|
|
|
|
|