Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

A simple fix would be to do a few checks before you make the substitution:

use strict; use warnings; use Data::Dumper qw{Dumper}; my %hash = ( 'GREETING1' => 'HAI', 'GREETING2' => 'HELLO', ); my $value = '-GREETING1- James -POSITION- -GREETING2- -FOO-'; ## find potential matches my @matches = $value =~ m/-([^\-\s]+)-/g; ## give summary print "" . (scalar@matches) . " matches for >>$value<<:\n" . (Dumper \ +@matches); ## check each potential match before substituting for my $match (@matches){ if (exists$hash{$match}){ # recognised? ## make substitution, including updates on string print "\t>$match< replaced:\n"; print "\tWAS : $value\n"; $value =~s/-$match-/$hash{$match}/; print "\tNOW : $value\n"; } else { print "$match not replaced.\n"; } }

Gives:

4 matches for >>-GREETING1- James -POSITION- -GREETING2- -FOO-<<: $VAR1 = [ 'GREETING1', 'POSITION', 'GREETING2', 'FOO' ]; >GREETING1< replaced: WAS : -GREETING1- James -POSITION- -GREETING2- -FOO- NOW : HAI James -POSITION- -GREETING2- -FOO- POSITION not replaced. >GREETING2< replaced: WAS : HAI James -POSITION- -GREETING2- -FOO- NOW : HAI James -POSITION- HELLO -FOO- FOO not replaced.

Not a one liner, but maybe a bit clearer to follow and easier to expand later... HTH!

Updated: Added some comments...

Just a something something...

In reply to Re: Substitution problem by BioLion
in thread Substitution problem by selva

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2024-04-25 14:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found