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:
Using Regular expresions stored in a scalar

 



pedrete
New User

Oct 24, 2012, 3:17 AM

Post #1 of 4 (834 views)
Using Regular expresions stored in a scalar Can't Post

I am new in the forum, so first of all... HELLO EVERYBODY! :-)

I am new to Perl and i hope lo learn as much as i can...

I have a small question that is making me crazy. I have a regex expresion in a scalar variable and i cannot use it:

$i="/hello/";
if ("helloeverybody" =~ $i) { print " OK ";}

Why this does not work???? :-(



Thanks in advance...



Pedrete.


BillKSmith
Veteran

Oct 24, 2012, 4:10 AM

Post #2 of 4 (830 views)
Re: [pedrete] Using Regular expresions stored in a scalar [In reply to] Can't Post


Code
use warnings; 
use strict;
my $i=qr/hello/;
if ("helloeverybody" =~ $i) {
print " OK ";
}


Strict and warnings are not required, but I strongly recommend that you develop the habit of always using them.

The my (refer: perdoc -f my) is required by strict.

The qr (refer to the section "quote and quotelike operators" in perdoc perlop) tells perl that the string is a regular expression and usually compiles it.

Regular expressions can be stored as strings, but then you need the slashes where they are used, not in the definition.
Good Luck,
Bill


Laurent_R
Veteran / Moderator

Oct 24, 2012, 4:18 AM

Post #3 of 4 (828 views)
Re: [pedrete] Using Regular expresions stored in a scalar [In reply to] Can't Post

You can also try this:


Code
my $i = "hello"; 
print "OK" if "helloeveryone" =~ /$i/;


This will print OK.


pedrete
New User

Oct 24, 2012, 4:50 AM

Post #4 of 4 (824 views)
Re: [Laurent_R] Using Regular expresions stored in a scalar [In reply to] Can't Post

Thanks a lot, Bill and Laurent...

it works!

Pedreter...

 
 


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

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