Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to learn source filter basics, after reading some documentation and trying out small examples. I wanted to work with some bigger ones. I find the given statement a lot more useful than the if-else structure. But the substitution isn't working inside the given structure.

The filter.

package filtertest; use Filter::Util::Call; use strict; use warnings; use feature "switch"; sub import { my $self = @_; my $ref = []; filter_add( bless $ref ); } sub filter { my $self = @_; my $status; $status = filter_read(); die "some thing messed up" if $status < 0 ; die "EOF reached" if $status == 0; given( $_ ){ when (/^say*/) { print "\n%%reaching here as $_ was matched%%"; s/say/print/; print "\n%%It was changed to $_%%"; } when ( /^use/ ) { print "\n&&reaching here as $_ was matched&&"; } default { print "\n**default condition**" } } $status; } 1;

The code I'm trying to run.

use strict; use warnings; use filtertest; say 'hello.world'; say 'hello';

The output is.

**default condition** **default condition** %%reaching here as say 'hello.world'; was matched%% %%It was changed to print 'hello.world'; String found where operator expected at filter_test.pl line 9, near "s +ay 'hello.world'" (Do you need to predeclare say?) %% **default condition** **default condition** %%reaching here as say 'hello'; was matched%% %%It was changed to print 'hello'; String found where operator expected at filter_test.pl line 12, near " +say 'hello'" (Do you need to predeclare say?) syntax error at filter_test.pl line 9, near "say 'hello.world'" EOF reached at filtertest.pm line 24. %%

What could be possibly going wrong?

Replies are listed 'Best First'.
Re: Source Filter basics
by ikegami (Patriarch) on Oct 05, 2010 at 07:18 UTC
    given doesn't alias $_ like a foreach loop does, it copies into a lexical $_. You didn't change the package var $_ as you should have.
    >perl -E"$_='abc'; say; given ($_) { s/abc/def/; say; } say;" abc def abc

    Switch given for for.

    >perl -E"$_='abc'; say; for ($_) { s/abc/def/; say; } say;" abc def def

    Note that if you simply want to provide say to older version of Perl, you can get something very similar from Perl6::Say.

Re: Source Filter basics
by Xiong (Hermit) on Oct 07, 2010 at 06:36 UTC

    Suggest you try Filter::Simple. It's not perfect but it's easier to use. This has nothing to do directly with your issue, of course.

    Feste: Misprison in the highest degree. Lady, cucullus non facit monachum. That's as much to say as, I wear not motley in my brain....