[Purdue-pm] Subroutine Attributes, or it's all my fault.
Dave Jacoby
jacoby.david at gmail.com
Tue Aug 21 08:57:41 PDT 2018
I won't start in on why I started looking at attributes (blame Matt S.
Trout), but
in looking at them, PerlTricks has a post showing how you can assign to a
function like a variable by setting lvalue.
I played with it some to get this:
package Foo;
use Scalar::Util qw(looks_like_number);
sub new { bless {}, shift }
sub iterate : lvalue {
my $self = shift;
$self->{iterate} = 0
if !defined $self->{iterate}
|| !looks_like_number( $self->{iterate} );
$self->{iterate} ++ ;
$self->{iterate};
}
This allows this:
my $i = Foo->new();
$i->iterate = 11;
while ( my $ii = $i->iterate ) {
say qq{\t$ii} ;
last if $ii >= 20;
}
Which gives us this:
12
13
14
15
16
17
18
19
20
To reiterate, you would expect $i->iterate(11), not $i->iterate = 11 .
This is a small change, and I might not ever use this in real life -- esp.,
if mst said (I think) that there's a problem with signature and attribute
order recently, meaning I couldn't write sub function ( $x ) { code }
anymore.
But...
my $i = Foo->new();
$i->iterate = -4;
while ( my $ii = $i->iterate ) {
say qq{\t$ii} ;
last if $ii >= 20;
}
gives use
-3
-2
-1
Something in Foo::iterate stops at 0. Zero should be defined. Zero should
look like a number.
Can anyone see the "stop iterating at zero" bug in my "toy code; don't use
in production" iterator?
--
Dave Jacoby
jacoby.david at gmail.com
Don't panic when the crisis is happening, or you won't enjoy it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/purdue-pm/attachments/20180821/5936dd06/attachment.html>
More information about the Purdue-pm
mailing list