in reply to Generic Parsing class with callback
I would force the caller to send in a callback instead of doing eval on a string...
use warnings; use strict; sub work { my ($x, $y, $callback) = @_; if (ref $callback ne 'CODE'){ die "callback param needs to be a code reference"; } $callback->($x, $y); } # with a ref to an existing sub sub this { my ($x, $y) = @_; print "$x $y\n"; } work(3, 4, \&this); # with an explicit code ref my $cref = sub { print "$_\n" for @_; }; work(2, 2, $cref); # or inline work(2, 3, sub { print "$_[0], $_[1]\n"; })
...and in your documentation, clearly state what parameters (the number and type) the callback should expect to receive.
It doesn't look like you need an eval later on either. eval is pretty much a try/catch to ensure no problems happened, and puts any errors it encounters in $@ so you can handle them gracefully. I think your else could be re-written as such (untested), given that it looks like you're only trying to see if a match was made, not the matches themselves:
my $regex = qr/$self->{regex}/; while(<$input>){ my $result = /$regex/; $self->{callback_ref}($result,$line,$output); }
-stevieb
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Generic Parsing class with callback
by QuillMeantTen (Friar) on Aug 31, 2015 at 20:50 UTC | |
by stevieb (Canon) on Aug 31, 2015 at 21:33 UTC |