CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Variable in sub. regex

 



Gabriele
Novice

Mar 20, 2016, 10:10 AM

Post #1 of 3 (1283 views)
Variable in sub. regex Can't Post

Hello everyone,

I am struggling to sort out a task.

I have a an array of substrings (ie. abc, klm) something like that.

Than I have a long sequence string, $sequence (ie abcdefghi.....etc).
NOTE: the smaller strings in the array above have been extracted from the long sequence, so they are definitely in the long sequence string.

I am working on a cgi script; what I want to do is to print $sequence highlighting all substrings of my array.

How can I use a variable in a substitution regex?
The code below does not work.

Code
 

my @array = ('abc', 'klm');
my $sequence = "abcdefghijklmnopq"

foreach my $value (@array) {
$sequence =~ s/$value/<b>$value</b>/;
}

print "<p> $sequence </p>";


# I have also tried using ! instead of / for the regex. Still nothing


(This post was edited by Gabriele on Mar 20, 2016, 10:12 AM)


BillKSmith
Veteran

Mar 20, 2016, 12:07 PM

Post #2 of 3 (1268 views)
Re: [Gabriele] Variable in sub. regex [In reply to] Can't Post

Using "!" instead of "/" in your substitution solves the ambiguity problem. You still get a compile-time error. True, the message is not very helpful. The message tells you that the error is in line 4 (nothing to do with the substitution). When you cannot find anything wrong with that line, check the line before it. You will find that you forgot the semicolon. With these two changes, your program will run correctly. You should always use "use strict;" and "use warnings;" and perhaps "use diagnostics;". In this case, diagnostics would have reminded you to check for the missing semicolon.

Code
use strict; 
use warnings;
use diagnostics;
my @array = ('abc', 'klm');
my $sequence = "abcdefghijklmnopq";

foreach my $value (@array) {
$sequence =~ s!$value!<b>$value</b>!;
}

print "<p> $sequence </p>";

Output:

Code
<p> <b>abc</b>defghij<b>klm</b>nopq </p>

Good Luck,
Bill


Gabriele
Novice

Mar 21, 2016, 8:22 AM

Post #3 of 3 (1253 views)
Re: [BillKSmith] Variable in sub. regex [In reply to] Can't Post

Thank you bill. It works.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives