local vs. my (was Re: code line of the day)
[email protected] (Chris Dolan) Fri, 8 Sep 2006 20:50:22 -0500
| Newsgroups | perl.fwp |
|---|---|
| Message-ID | <[email protected]> |
On Sep 8, 2006, at 6:48 PM, A. Pagaltzis wrote: > * Chris Dolan <[email protected]> [2006-09-08 17:10]: >> Why did you use "local"? Shouldn't the following work? >> >> sub flatten_copy { >> my $s = shift; >> ref $s eq 'SCALAR' ? "$$s" : "$s"; >> } > > Works the same. I often use `local $_` in tiny functions that > mangle just a single value. Matter of taste/style. Ahh, I see -- cargo cult. ;-) Changing the topic a little bit... I've always suspected there was a speed difference between local and my. So, I just benchmarked the two versions, and "my" wins by a wide margin: % perl test.pl Rate local my local 467290/s -- -33% my 699301/s 50% -- % perl -v This is perl, v5.8.6 built for darwin-thread-multi-2level (with 2 registered patches, see perl -V for more detail) ============= test.pl ============== #!/usr/bin/perl -w use strict; use Benchmark qw(cmpthese); my $s = 'foo'; $_ = 'foo'; cmpthese(1_000_000, { 'local' => sub { flatten_copy_local('bar'); }, 'my' => sub { flatten_copy_my('bar'); }, }); sub flatten_copy_local { local $_ = shift; ref $_ eq 'SCALAR' ? "$$_" : "$_"; } sub flatten_copy_my { my $s = shift; ref $s eq 'SCALAR' ? "$$s" : "$s"; } ======================================== -- Chris Dolan, Software Developer, Clotho Advanced Media Inc. 608-294-7900, fax 294-7025, 1435 E Main St, Madison WI 53703 vCard: http://www.chrisdolan.net/ChrisDolan.vcf Clotho Advanced Media, Inc. - Creators of MediaLandscape Software (http://www.media-landscape.com/) and partners in the revolutionary Croquet project (http://www.opencroquet.org/)