Module to prevent eval'd code from using $&, $' and $`. Use at your own risk; this will result in symbol table entries with the FAKE flag (which is supposed to only occur on non-symbol table globs).

Update: removed unused confess

Update: to clarify, this will prevent the performance degradation that occurs through use of $&, $', and $` (so long as AmpKiller is use'd before code that uses one of the variables is even compiled). It also will croak if code actually tries to use one of the variables at run-time. If you do:

use AmpKiller; if ("foo" =~ /bar/) { print $& }
no croak will be done, since $& didn't actually get used.
package AmpKiller; # usage: # eval $some_code_that_may_use_dollerampersand; # die "Sorry, can't do that: $@" if $@ && $@=~/Use of .* disallowed/; use strict; use warnings; use Carp 'croak'; sub TIESCALAR { my $var = $_[1]; bless \$var } sub FETCH { croak "Use of ${$_[0]} disallowed" } sub STORE { croak "Modification of a read-only value attempted" } tie our $amp, __PACKAGE__, '$&'; tie our $backtick, __PACKAGE__, '$`'; tie our $tick, __PACKAGE__, '$\''; $::{"&"} = *amp; $::{"'"} = *tick; $::{"`"} = *backtick; 1;

Replies are listed 'Best First'.
Re: AmpKiller.pm to disallow $&, etc.
by Abigail-II (Bishop) on Jan 27, 2004 at 09:38 UTC
    That module only "works" if the flow of the program actually fetches $&. The following program has $& in it (and hence, penalties occur), but the FETCH is never triggered:
    #!/usr/bin/perl use strict; use warnings; use AmpKiller; "foo" =~ /o/; if (@ARGV) { print $&, "\n"; } print "The End\n"; __END__ The End

    Abigail

      No, penalties do not occur, as you can verify with Devel::SawAmpersand. Because I set a *& glob up, the code in gv_fetchpv to set up a new variable isn't triggered. The only purpose of croaking is to detect problems in eval'd code as a result of disabling $&.