Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: How do I pass $1 to s///?

by ikegami (Patriarch)
on Jan 06, 2006 at 16:56 UTC ( [id://521539]=note: print w/replies, xml ) Need Help??


in reply to How do I pass $1 to s///?

Your $1 gets interpolated too early. What you really need is a templating system, but you can use the following in the meanwhile:

sub foo { (my $text = $_[0]) =~ s/$_[1]/eval $_[2]/e; print $text; } foo("This is test 1\n", qr/test (.*)/, '"fish $1"');

(Insert notice of hazards of using eval EXPR here.)

Replies are listed 'Best First'.
Re^2: How do I pass $1 to s///?
by Anonymous Monk on Jan 06, 2006 at 19:19 UTC
    No need to use eval, I'd prefer one of...
    sub foo { (my $text = $_[0]) =~ s/$_[1]/$_[2]->($1)/e; print $text; } foo("This is test 1\n", qr/test (.*)/, sub{"fish $_[0]"});
    ...or...
    sub foo { (my $text = $_[0]) =~ s/$_[1]/$_[2]->()/e; print $text; } foo("This is test 1\n", qr/test (.*)/, sub{"fish $1"});
      Nice, as long as the parameters of foo aren't read a file.
        ~/perl/monks$ cat foo.txt sub{"fish $_[0]"};
        ...then...
        $foo_from_file = do "foo.txt"; foo("This is test 1\n", qr/test (.*)/, $foo_from_file); sub foo { (my $text = $_[0]) =~ s/$_[1]/$_[2]->($1)/e; print $text; }
Re^2: How do I pass $1 to s///?
by Anonymous Monk on Jan 06, 2006 at 17:19 UTC
    Slightly nicer as...
    (my $text = $_[0]) =~ s/$_[1]/$_[2]/ee;
      I call that uglier since it hides the eval. eval EXPR is something that should be glaring, blinking and alarming.
Re^2: How do I pass $1 to s///?
by Anonymous Monk on Jan 06, 2006 at 17:07 UTC
    Ah, thankyou! The only problem is that I want to pass a much more complicated string in than "fish $1"... What do you mean by a templating system? Can you point me at a webpage or something? Thanks for the replies BTW! It's most appreciated! (You monks reply fast too! :)

      You can pass any Perl source code in the above snippet (which is why it's potentially dangerous).

      One templating system would be the Template Toolkit.

      use Template; sub foo { my $template = Template->new(); (my $text = $_[0]) =~ s/$_[1]/ my $output = ''; my @matches = map { substr($text, $-[$_], $+[$_] - $-[$_]) } 1 .. $#-; $template->process(\$_[2], { matches => \@matches }, \$output); $output /e; print $text; } foo("This is test 1\n", qr/test (.*)/, 'fish [% matches.1 %]');

      (Untested)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://521539]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2024-04-19 07:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found