A nice perl feature
Wednesday, October 13th, 2010Recently I have been proofreading the Perl 5.12.1 documentation (for a printed edition, Volume 1 (Language Reference) is just published).
I picked up a few new tricks. The one I am using the most is the new “//” operator. ($a // $b is equivalent to defined($a) ? $a : $b.) Now it’s possible to assign a default value to a variable if it’s undefined with just $foo //= $default, keeping the original value if it already exists.
This is handy because in Perl zero evaluates to false and it used to be common to find code like $foo ||= 1, to set foo to a default value of 1. This looks like it does the right thing but overwrites the existing value when $foo has a value of 0.