in reply to dynamic regex variable

How about:

sub check_logs { my $regx_maker = shift(@_); my @clients = qw(abc def hij); foreach my $client (@clients) { my $regx = &$regx_maker($client); print($regx, "\n"); } } foreach my $regx_maker ( sub { my $client = shift; qr/pre-${client}-post/ }, sub { my $client = shift; qr/foo-${client}-bar/ }, ) { check_logs($regx_maker); } __END__ output ====== (?-xism:pre-abc-post) (?-xism:pre-def-post) (?-xism:pre-hij-post) (?-xism:foo-abc-bar) (?-xism:foo-def-bar) (?-xism:foo-hij-bar)

Replies are listed 'Best First'.
Re^2: dynamic regex variable
by ikegami (Patriarch) on Oct 02, 2004 at 03:29 UTC

    Here's an alternative that matches your specs without using eval:

    sub check_logs { my $regx_template = shift(@_); my @clients = qw(abc def hij); foreach my $client (@clients) { my $regx = $regx_template; $regx =~ s/\\\$(?:client\b|{client})/$client/g; print($regx, "\n"); } } foreach my $regx_template ( qr/pre-\$client-post/, qr/foo-\$client-bar/, qr/moo\${client}moo/, ) { check_logs($regx_template); } __END__ output ====== (?-xism:pre-abc-post) (?-xism:pre-def-post) (?-xism:pre-hij-post) (?-xism:foo-abc-bar) (?-xism:foo-def-bar) (?-xism:foo-hij-bar) (?-xism:mooabcmoo) (?-xism:moodefmoo) (?-xism:moohijmoo)