kiat has asked for the wisdom of the Perl Monks concerning the following question:

$pattern = 'match'; @array = ('hello', 'matched', 'match', 123, 'sleep'); foreach (@array) { # Matched 'match' but not 'matched' print "$1\n" if /\b($pattern)\b/; #print "$1\n" if /(\b$pattern\b)/; }

Should I put the '\b' inside the brackets or outside them? Please advise and thanks in advance :)

Edited 2001-11-02 by Ovid

Replies are listed 'Best First'.
Re: regular expression
by blakem (Monsignor) on Nov 03, 2001 at 06:25 UTC
    \b is a zero-width assertion, so I don't think it matters one way or the other...
    /\b($patt)\b/ wont behave any differently than /(\b$patt\b)/, though the first one looks clearer to my eyes.

    p.s. When posting code to perlmonks, you should surrond your code with CODE tags.

    <CODE>my $perl = 'stuff';</CODE>

    -Blake

Re: regular expression
by staeryatz (Monk) on Nov 03, 2001 at 07:34 UTC
    Another explaination behind the answer...

    With regex's and meta characters, it depends on whether or not you want to join the meta character with the pattern as a single atom.

    If the meta character is placed in the parenthesis with a pattern, then it'll be included in as part of the backreference variable.

    In your case with using the meta character \b, the "word boundary", it is not something that represents (a) character(s), therefore it wouldn't show up in the backreference variable.

Re: regular expression
by hopes (Friar) on Nov 03, 2001 at 17:34 UTC
    Just another comment, since blake's and staeryatz's has pointed something like that.
    \b is the word boundary, and is zero length.
    It can be said that \b is "the nothing before and after a word"
    Because of that, it is indiferent to code
    /\b($pattern)\b/ or this
    /(\b$pattern\b)/
    I agree with blake, the first is better readable for me.
    Hopes
Re: regular expression
by kiat (Vicar) on Nov 06, 2001 at 16:40 UTC
    thanks guys for helping :) i now understand better what \b means.