As others have said, the code provides a default anonymous sub for the 'Post' attribute of $self. Since the anonymous sub aspect of this has been well covered, I'll comment on the default value side of things, with a slight detour into 'or' vs '||';
The code snippet you posted threw me off balance for half a second--setting default values is usually done using '||'--the high precedence logical or operator.
Perl has two logical or operators, '||' and 'or'. They identical except in terms of precedence. '||' has a high precedence and 'or' has a low precedence.
$foo = $bar || 'baz'; # is identical to $foo = ( $bar or 'baz');
Common usage for each operator:
open( $fh, '>', $filename ) or die "Unable to open file: $!"; my $foo = $bar || 'baz';
Now, lets look at a couple ways to set a default value:
# Original code $self->{'Post'} = ($args{'Post'} or sub {1;}); # High precedence or $self->{'Post'} = $args{'Post'} || sub {1}; # Ternary operator $self->{'Post'} = $args{'Post'} ? $args{'Post') : sub {1}; # Using '||' for a numeric value. $self->{'Number'} = $args{'Number'} || 10;
This idiom is a common, compact, and readable way to set default values. However there is a trap for the unwary here. If the value you are testing may legitimately evaluate to false, your default value will be spuriously assigned. Take a look at the code below for an example of this bug.
foo(); foo(23); foo(0); sub foo { my $number = shift || 10; print "My number is $number\n"; } __END__ #OUTPUT: My number is 10 My number is 23 My number is 10
So, if you use this idiom, make sure you understand how your acceptable values are treated in boolean context (whether they evaluate to TRUE or FALSE).
Update: as DrHyde points out, if you are using Perl 5.10, the truly lovely defined-or operator solves this problem very nicely.
foo(); foo(23); foo(0); sub foo { my $number = shift // 10; print "My number is $number\n"; } __END__ #OUTPUT: My number is 10 My number is 23 My number is 0
TGI says moo
In reply to Re: what is sub {1;}
by TGI
in thread what is sub {1;}
by mlgvalt
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |