What's the best way to assign value to variable "false" in perl

I know that in Perl, I know that there are many ways to do many things, and I was wondering what is the best (most efficient, most real, fastest) way to assign a value to a variable that is false (0, empty string, undef, etc. etc.), some of which I know:

if ( ! $x ) {
    $x = 1;
# or $x = 1 if ( ! $x );

$x = $x || 1;

$x = 1 unless $x;

$x ||= 1;


Is there a better option?


source to share

2 answers

$x ||= $default;


is short, clear, fast, and commonly used (i.e. readable).



You might want to add the //

and //=

(certainty checks) operators . Having said that, if the difference in speed between these methods really matters to your program, you might want to move parts of your algorithm outside of perl and call it from perl instead (using perl as "glue").

As the pedantic police blinded all over in the comments, I took the time to compare it. Not the best benchmarking in the world, but still I ran:

time perl -e 'my $a; for (1..10000000) { $a ||= $_; }; print $a;'

time perl -e 'my $a; for (1..10000000) { $a //= $_; }; print $a;'

On my system, the version is //=

consistently 5-10% faster. YMMV.

Assuming the quotes around "false" in the original question mean "false" and not strictly fake, and further assuming undef is a valid "false" value in this context, the undef version of the operator is about 5-10% faster.

Assuming the author of the question is looking for the fastest way to initialize an uninitialized variable, //=

it is probably faster based on simple tests I did, although my comments on optimizations in perl are still at this level.



All Articles