[ABE.pm] perl 5.10 rules! - the // operator
Ricardo SIGNES
rjbs-perl-abe at lists.manxome.org
Tue May 29 19:46:26 PDT 2007
Here's a little one, but a goodie: the // operator.
I do this sort of thing all the time:
# This routine takes a bunch of lines and indents all but the first, padding
# the lines with $indent spaces on the left.
sub hanging_indent {
my ($paragraph, $indent) = @_;
$indent ||= 2;
my @lines = split /\n/, $paragraph;
my $new_string = shift @lines;
for my $line (@lines) {
$new_string .= ' ' x $indent . "$_\n";
}
return $new_string;
}
So, it's a contrived example, but you get the point. The problem here is the
default $indent. If I call it like this:
hanging_indent($string);
It's swell, I get two-space indents, which are the default. If I call it like,
this, though:
hanging_indent($string, 0);
...I still get two-space indents! See, ||= means "assign unless the thing on
the left is already true." Well, zero isn't true!
This means I end up writing things like:
$indent = 2 unless defined $indent;
or
$indent = defined $indent ? $indent : 2;
Ugh! // to the rescue! // is just like ||, except instead of checking for
truth, it checks for definedness. If the thing on the left is defined, it will
short circuit there, even if it's defined as a false value like zero or the
empty string. I can rewrite my routine, saying:
$indent //= 2;
...and now I can pass a zero successfully!
--
rjbs
More information about the ABE-pm
mailing list