AgA
AgA

Reputation: 2126

unable to check for a pattern in a string

All I want to check is that whether "free" occurs in word boundary or not and this is not working(prints nothing):

use strict;

my @words= ("free hotmail msn");

my $free = "free";

$free =~ s/.*/\b$&\b/;


if ( $words[0] =~ m/$free/)
{
    print "found\n";
}

Upvotes: 3

Views: 73

Answers (2)

mob
mob

Reputation: 118595

In a pattern replacement, as in a double quoted string, \b is interpreted as the backspace character (chr(8) on most systems).

$free =~ s/.*/\\b$&\\b/;

is an awkward way of writing one of

$free = '\b' . $free . '\b';
$free = "\\b$free\\b";

but it will do the job.

Upvotes: 1

Borodin
Borodin

Reputation: 126722

All you need to do is write

my $free = 'free';

$free = qr/\b$free\b/;

print "found" if $words[0] =~ $free;

But if your @words array is supposed to contain a single word per element then you are more likely to want

use strict;
use warnings;

my @words= qw( free hotmail msn );

my $free = "free";

print "found\n" if $words[0] eq $free;

Upvotes: 2

Related Questions