http://www.perlmonks.org?node_id=803851


in reply to Check exist of anonymous subroutine before calling it within regexp substitute?

If it were my code, I'd probably write it the way moritz has it, but if you're extra paranoid, you might do something like this:

($out_message = $log_format) =~ s{%(.)}{ my $m = $meta_char{$1}; (ref sub {} eq ref $m) ? $m->() : $1 }ge;

That will withstand missing elements as well as elements that exist but don't have a code reference in them.

Replies are listed 'Best First'.
Re^2: Check exist of anonymous subroutine before calling it within regexp substitute?
by jffry (Hermit) on Oct 29, 2009 at 17:25 UTC

    Minor tangent...

    You swapped out the regexp delimiters from slashes to curly braces, but to me, this seems harder to read. I can only conclude that you think the curly braces improve readability. I'm guessing when you read the code, your mind's parser is thinking, "a block is a block so I expect curly braces" or something like that?

      I often write s/// replacements (and m// matches) with braces, mostly because I don't have to escape slashes, and I don't even have to escape braces as long as they're nested. It's not unusual that I want to match a string with a slash in it (usually a file path), so I find using any "not slash" as delimiters useful.

      That said, I don't make a habit of changing delimiters in existing code. I probably would have stayed with slashes in my reply here if not for the /e flag. Since the replacement is being executed as a code block, I think it's good to make it look like a code block.