Cool Perl Trick
I was exploring some ideas I had floating around in my head and I came across the ||= operator in a perl man page example. I didn't recall having seen that before, so I looked it up. Turns out that it's a very cool operator and highly useful.
Here's an example. Say you have this script:
#!/bin/perl
$foo = "on";
if ($foo = undef) {
$foo = "off";
}
print "Variable is $foo\n";
Kind of a stupid example here, but you get the point: if there's nothing assigned to $foo, set it to equal the string "off". Which is fine thing to want to do in this sort of style, especially if the assignment and the if loop are acres apart, script-wise. (I'd tend to write that with "unless ($foo) {" since it's essentailly a negative test, but the point is the same and it's easier to see this way.)
Turns out the ||= operator does this. The following is identical to the above script:
#!/bin/perl
$foo = "on";
print "Variable is ", $foo ||= "off", "\n";
You can comment out the '$foo = "on";' line in either and it will print "Variable is off"; Expanded out to be more clear, that is equivalent to this:
#!/bin/perl
$foo = "on";
$foo ||= "off";
print "Variable is $foo\n";
Which looks even sillier than the first script, but remeber that $foo might have come from either STDIN (keyboard) or a config file value (which may not have been there, file may not exist, etc), or whatever. Could be a database handle read. The select returns nothing, so you give it something. With no big for loop to get in the way. Very handy for like setting a bunch of defaults en masse.
Anyway, I thought it was nice enough to share. It's something I wish I would have found out about a long time ago. For those of you not perlish, forgive the propeller headed intrusion... :-)