in reply to Re^2: Using pattern match
in thread Using pattern match

Yes, you will definitely need string eval here.

Something like this:

#!/usr/bin/perl -w use strict; # builtin triggers my %triggers; # add triggers from params my $trigger_name = shift @ARGV; my $trigger_action_str = shift @ARGV; $triggers{$trigger_name} = $trigger_action_str; my $buff = "You are fired!"; foreach my $trigger ( keys ( %triggers ) ) { if ( $buff =~ /$trigger/ ) { print eval '"' . $triggers{$trigger} . '\n"'; } }

But this is not a design anyone will recommend.

Besides, this will not run in taint mode.

Replies are listed 'Best First'.
Re^4: Using pattern match
by tceng (Novice) on Aug 10, 2007 at 14:50 UTC
    Thanks akho. I ended up with this, can you please advise?
    #!/usr/bin/perl -w use strict; # builtin triggers my %triggers; # add triggers from params my $trigger_name = shift @ARGV; my $trigger_action_str = shift @ARGV; $triggers{$trigger_name} = sub { eval $trigger_action_str; }; my $buff = "You are fired!"; foreach my $trigger ( keys ( %triggers ) ) { if ( $buff =~ /$trigger/ ) { print &{$triggers{$trigger}}; } }
    If I try:
    perl triggers2.pl "You are (\w+)." "\"You are: $1\""
    I get:
    You are: fired

    Correct. You see, I just have to add escaped quotes on the command line. But is this one a good way to go, pls?

    Cheers,

    tceng
      You can add the quotes in sub's definition.

      This is not a very good idea for the same reasons as my eval-based solution above: it's insecure (there was a comment above about that) and the interface (the way you call triggers.pl) depends on the implementation in weird ways (the user has to use numbered variables).

      This is ok if you just want to learn about dispatch tables, but production code should be better designed.