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

Re: multiple substitutions

by IndyZ (Friar)
on Apr 10, 2002 at 05:12 UTC ( #157959=note: print w/replies, xml ) Need Help??

in reply to multiple substitutions

Try the global match (g) and eval (e) flags. Here's an example:
#!/usr/local/bin/perl while (<>) { s/([A-Z]+)/reverse($1)/ge; print; }
The first part is obvious: It matches 1 or more capital characters in the range A-Z, and grabs it to $1. The 'e' flag on the regexp causes the the 'reverse($1)' to be eval'd and the return value to be substituted in, and the 'g' flag makes as many matches as possible. This particular example reverses any and all sections of capital letters so "LREP java PYTHON" would become "PERL java NOHTYP".

Instead of using the reverse function, write your own function to do the database access, pass it the matched data and have it return what should be substituted in.

Just a warning: I haven't run any benchmarks or anything, but this will probably cause a pretty big speed hit since you are running an eval() on every match.

Here are my untested changes to your code. It may or may not work.

sub getfromdb { $diagId = shift; $dbh = ConnectDB($User, $Password); $sql = "SELECT version FROM diagramversion WHERE diagram_id='$ +diagId' AND workflow_state='Stored'"; #to_char(version,'099') didn't + work $sth = RunJobDB($dbh, $sql); @version = $sth->fetchrow_array; $version = $version[0]; $sth->finish(); DisconnectDB($dbh); $version = sprintf( "%03d", $version ); $fullId = $diagId."-".$version; return("$fullId"); } $$imageMap =~ s/\?name=(.*?)_DIAGLINK/getfromdb($1)/gei;

Yet Another Update:
Variable names like '$$imageMap' are very difficult to maintain and it's almost impossible to make sure you don't walk all over important variables. Try using a hash instead.


Replies are listed 'Best First'.
Isn't there an "e" missing?
by RMGir (Prior) on Apr 10, 2002 at 11:40 UTC
    <quote> $$imageMap =~ s/\?name=(.*?)_DIAGLINK/getfromdb($1)/gxi; </quote>
    - - - - - - - - - - - - - - - - - - - -

    Shouldn't there be an "e" in the options?

    $$imageMap =~ s/\?name=(.*?)_DIAGLINK/getfromdb($1)/gxie;
    Otherwise, you'll be replacing with a literal "getfromdb(whateverdollar1matched)", I think...
      Yep, you're right. This is what I get for typing on no sleep. The example has been fixed.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2022-08-10 01:29 GMT
Find Nodes?
    Voting Booth?

    No recent polls found