Chon-Ji has asked for the wisdom of the Perl Monks concerning the following question:

Hello! Need a little help for my project.

I have this array of strings, say some thing like:
x101032 x101822 x101209 x102292 x101302 x102938 x102943 x101289
What I want to do is get a subset of the array containg all the strings that have the substring "102" in them. In this case: the new array would contain
x102292 x102938 x102943
One approach is to use a for/while loop, but is there a much efficient way to do this? thanks.

Code tags and formatting added by holli

Replies are listed 'Best First'.
Re: Array manipulation
by GrandFather (Saint) on May 30, 2006 at 06:52 UTC

    Show us the code you have tried. grep would seem to be the best answer, but there may be stuff going on that is not obvious from your description.


    DWIM is Perl's answer to Gödel
Re: Array manipulation
by l.frankline (Hermit) on May 30, 2006 at 06:59 UTC

    hi,

    try the below code...

    @arr = qw/x101032 x101822 x101209 x102292 x101302 x102938 x102943 x101 +289/; @new = grep /^x102/,@arr; print "@new\n";

    Output is:

    x102292 x102938 x102943

    regards,
    Franklin

    Don't put off till tomorrow, what you can do today.

Re: Array manipulation
by Chon-Ji (Novice) on May 30, 2006 at 07:13 UTC
    i've been told that grep is slow for perl, is that true? I'll be processing. I'll be processing thousands of strings so I'm trying to minimize loops as much as possible
      You're going to have to loop through the array in some fashion. Obviously you have to look at each element to determine if it's in your wanted set, right? grep is just a single loop and is probably faster than doing a foreach and pushing the matching elements onto a new array. When in doubt, Benchmark.
        Ok in that case, would it be possible to have an array as the first input to grep? Basically,I just want to have more than 1 search string. Modifying the problem a bit, let's say now I want to get the subset that has the subtring 102 or 101 in them. thanks