kaatunut has asked for the wisdom of the Perl Monks concerning the following question:
Case: I want a function called 'on' that will take two code blocks, 'when' ($_ = line to be matched, returns true if matches) and 'then' (if 'when' was true, run 'then' with $_ = modifiable typeglob to the line to be matched).
Clarification:
then={ /foo/ }
when={ tr/ab/ba/; }
$line="abba is kind of foo";
After calling on with proper parameters,
$line eq "baab is kind of foo"
After tinkering for a while (and reading the try/catch example), I came up with this:
sub on (&$$) { my($f1,$f2,$l)=@_; local $_=$$l; if (&$f1) { local *_=$l; &$f2($l); } } sub action (&) { shift } $a="abba is foo"; on { /foo/ } action { tr/ab/ba/; },\$a; print "$a\n";
And lo! It works. Now, what's the point, and why is this in Seekers, you ask. Well...
At this point it becomes evident how similar this is to perl grep. However, grep has one magical power I don't: It can take EXPR or BLOCK as its 1st parameter. How do I?
Intuitive solution one, write two functions called 'on' with different prototypes. Meep! Prototype mismatch.
Intuitive solution two, ditch prototypes and figure out what we are doing by looking at the parameter list. Meep! Syntax error follows.
How do I manage?
Issue two, rather minor though, is that I'd like to rid myself of the 'action' keyword and just write the two code blocks like this: on { /foo/ } { tr/ab/ba/; },\$a;
But I couldn't figure out any way to do without that dummy sub action, everything resulted in obscure syntax errors.
-Kaatunut
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Polymorphic prototypes? (creating new syntax)
by Corion (Patriarch) on Apr 08, 2001 at 16:32 UTC | |
|
Re (tilly) 1: Polymorphic prototypes? (creating new syntax)
by tilly (Archbishop) on Apr 08, 2001 at 19:46 UTC | |
by kaatunut (Scribe) on Apr 08, 2001 at 22:27 UTC | |
by tilly (Archbishop) on Apr 08, 2001 at 22:36 UTC | |
by princepawn (Parson) on Apr 09, 2001 at 21:01 UTC | |
by princepawn (Parson) on Apr 09, 2001 at 21:02 UTC | |
by tilly (Archbishop) on Apr 09, 2001 at 21:12 UTC |