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

Hello,

I have a long line of text and I am searching it with a regexp. However, I want to store all strings matched by the regexp into an array even though the strings may not be identical.

An example; searching:

1 2 blue 4 yellow orange 6 7 yello purple ellow

I want to pull out yellow, yello and ellow into an array.

I can write the regexp to match ello trailing or followed by any number of letters - \w*ello\w* - but how do I store the different strings found in the one line into an array?

Thanks.

Replies are listed 'Best First'.
Re: Storing more than one regexp match in a line
by kschwab (Vicar) on Jul 28, 2001 at 17:54 UTC
    #!/usr/bin/perl $_="1 2 blue 4 yellow orange 6 7 yello purple ellow"; my @matches=/(\w*ello\w*)/g; foreach my $one (@matches) { print "[$one]\n"; }

    results in:

    $ perl tester [yellow] [yello] [ellow]
    Update:removed useless parens around @matches. duh. thanks Albannach.

    Update 2: Perhaps some text from perlfunc would help explain what's happening:

    The /g modifier specifies global pattern matching--
    that is, matching as many times as possible within
    the string.  How it behaves depends on the context.
    In list context, it returns a list of all the
    substrings matched by all the parentheses in the
    regular expression.