Regex, spaces in pattern stored in variable.

J

Justin C

I have a list of strings, some contain spaces. The strings are used as
patterns for a regex match, they don't seem to be working! I tried
substituting the space with '\s' but I got warnings, and still no match.

I'm sure there's a way to do this, but Google isn't providing any
answers (more likely I don't know how to formulate a useful search).

Anyway, here's what I have:

#!/usr/bin/perl

use warnings;
use strict;

my @list = (
"Fred Flintstone",
"Barney Rubble",
);

while (<DATA>) {
my $string = chomp $_;
foreach (@list) {
if ( $string =~ /($_)/ ) {
print "Matched ", $1, "\n";
}
}
}

__DATA__
A man called Fred Flintstone lives in a cave.
Fred's neighbour is called Barney Rubble.
Fred is married to Wilma Flintstone and Barney Rubble is married to Betty.

Justin.
 
P

Peter Makholm

Justin C said:
#!/usr/bin/perl

use warnings;
use strict;

my @list = (
"Fred Flintstone",
"Barney Rubble",
);

while (<DATA>) {
my $string = chomp $_;

'perldoc -f chomp' says:

[...] It returns the total number of characters removed from all its
arguments. [...]

So $string would have the value 1. Using the perl debugger it would
have been very easy to check that you assumptions about the content of
$string and $_ was true at the conditional.
 
J

Justin C

Justin C said:
#!/usr/bin/perl

use warnings;
use strict;

my @list = (
"Fred Flintstone",
"Barney Rubble",
);

while (<DATA>) {
my $string = chomp $_;

'perldoc -f chomp' says:

[...] It returns the total number of characters removed from all its
arguments. [...]

Doh!

Thank you.

Justin.
 
J

Justin C

It's very confusing to have several nested loops all looping with $_.
You're telling me!

for my $match (@list) {


You normally want \Q\E when interpolating a plain string into a regex:

if (/(\Q$match\E)/) {

Ah, yes, I see. That makes sense (this is, I think, my first pattern in
a scalar).


Justin.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top