Gossamer Forum
Home : General : Perl Programming :

shift vs $_[0]

Quote Reply
shift vs $_[0]
Could anyone tell me the difference between:

my ($errormsg) = $_[0];

and:

my ($errormsg) = shift;

Or is there no difference? ...but then: wich one is better, quicker?

And I would like to comments out the following lines. But can It be harmfull? Especially the first line.

Code:
# If the form name is not attach, then we need to parse this like
# regular form data and need to remove any field with "---" as a value
# (as this denotes an empty SELECT field.)
if ($name ne "attach") {
$body =~ tr/ / /;
$body =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
# $body =~ s///g;
# $body =~ s/\n/
/g;
# $body =~ s/\r//g;
if ($body ne "---") {
exists $ATTACH{$name} ? ($ATTACH{$name} .= "~~$body") : ($ATTACH{$name} = $body);
}
Quote Reply
Re: shift vs $_[0] In reply to
using shift is just a little faster to type to most people and some might say easier to work with or maintain in various situations. in actuality, using the $_[0] method gives you a faster program as it doesn't have to process a command to get the result. i benchmarked them both and consistently got results like these:

Code:
Benchmark: timing 500000 iterations of other, shift...
other: 2 wallclock secs ( 1.37 usr + 0.00 sys = 1.37 CPU) @ 364963.50/s (n=500000)
shift: 1 wallclock secs ( 1.64 usr + 0.00 sys = 1.64 CPU) @ 304878.05/s (n=500000)
(keep in mind, the cpu time is what is important, not the wallclock. if i name 'other' to 'zther' it comes out faster in wallclocks too as the perl interp has already been initiallized by the time it gets to it)
-- Gordon


s/(\d{2})/chr($1)/ge + print if $_ = '8284703280698276687967';
Quote Reply
Re: shift vs $_[0] In reply to
Thanks for your very valuable input!

Because I'm working on a a script to handle form input and attachments I would like to check the speed of the written script. Could you please tell me how I could measure the benchmarks of my script.


Quote Reply
Re: shift vs $_[0] In reply to
the Benchmark module comes with all distros of perl now. Check out the man page for it to get all of the methods of using it. An example (the code i used for this) is as follows:

Code:
use Benchmark;
my $num_of_iterations = 500000;
timethese ($num_of_iterations, {
'other' => 'grabit(2); sub grabit {my $a = $_[0]; return $a;}',
'shift' => 'grabit(2); sub grabit {my $a = shift; return $a;}',
});
-- Gordon


s/(\d{2})/chr($1)/ge + print if $_ = '8284703280698276687967';