in reply to greedy search

$str = 'aaaaa'; $str =~ s/a+/b/;

Since '+' is greedy, you end up with 'b' in $str.
If '+' wasn't greedy, you'd end up with 'baaaa' in $str.

You can make '+' non-greedy by following it with a '?':

$str1 = $str2 = '111b222c333c444'; $str1 =~ s/b.+c//; # $str1 contains '111444'. $str2 =~ s/b.+?c//; # $str2 contains ''111333c444'.

'*' and '?' can similarly be modified with a '?'.

Both greedy and non-greedy are useful. Use whichever one you need in a particular situation.

Replies are listed 'Best First'.
Re^2: greedy search
by monarch (Priest) on Jun 03, 2005 at 05:45 UTC
    Searches are greedy by default. But one situation where you want a non-greedy search that is fairly common is finding the contents of an HTML tag.

    Let's say you have:

    <a href="?"><b>Hello</b></a>

    If you pattern match using /<(.+)>/ your match will contain "a href="?"><b>Hello</b></a".

    If you pattern match using /<(.+?)>/ your match will contain "a href="?"", which is usually what people are looking for.

    Having the option is great, more power in your hands to find what you want!