One small point: if you are doing a lot of different substitutions, you may feel tempted to do something like

$text =~ s/(\W+)/$1->()/eg; # replace any nonwhitespace characters wit +h the result of a function call

The danger is that unless you trust the file being fed into the program, someone might feed you a word that called some bad subroutine in your program. Or it might just happen accidentally!

To make sure this doesn't happen, set up a hash of subroutine references(I think this could be called a "dispatch table"):

%subs = ( bar => \&bar foo => \&foo do_something => \&do_something ); $text =~ s/(\W+)/$subs{$1}->() if defined $subs{$1}/eg; # only call fr +om a list of specific subroutines

The $subs{$1}->() is calling the subroutine reference (coderef) defined in the hash, so for example "bar" would be replaced by the result of the "bar" subroutine.

dave hj~


In reply to Re: replacing text with a function by dash2
in thread replacing text with a function by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.