On Thu, 22 Nov 2018 13:48:18 +0000
James Kerwin <[email protected]> wrote:
> Hi All,
>
> I'm looking through some Perl files for software we use and I noticed
> this in one of the config files:
>
> $c->{guess_doc_type} ||= sub {
>
> All other similar config files show a similar structure, but without
> the "||" before the equals sign:
>
> $c->{validate_document} = sub {
>
> My question is, what is the "||" doing in the first example?
"||=" is the conditional assignment operator - it assigns the value on
the right-hand side to the thing on the left hand side, *but* only if
the thing on the left hand side doesn't evaluate to a true value.
For instance,
my $foo;
$foo ||= "Bar";
# $foo is now "Bar" - because it wasn't true before
$foo ||= "Baz";
# $foo is still "Bar" - it wasn't changed
In your example, the value on the right hand side is a coderef = so, if
$c->{guess_doc_type} didn't already contain something truthy, then it
will be set to a coderef defined by the sub { ... } block.
See also "//=", the defined-or operator, which works in pretty much the
same way, but checking for definedness - the difference being that if
the left hand side contained something that wasn't a truthy value, ||=
would overwrite it, whereas //= wouldn't.
You'll often see these operators used to provide default values.
e.g.
sub hello {
my $name = shift;
$name ||= 'Anonymous Person';
return "Hi there, $name!";
}
> I've attempted to Google this, but found no solid answer.
Yeah, Googling for operators when you don't know their name is rarely
useful :) Perl's operators are all documented quite well at:
https://perldoc.perl.org/perlop.html
I do notice that there isn't actually a very useful section on ||=
and //= - I may try to raise a pull requests to add more documentation
on them.
Cheers
Dave P
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/