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

I have an array of words so I need to find position specific word like "DATA LIST" in an array , but the thing is in array it can have spaces before or after it like " DATA LIST " so how can i find this word truncating the spaces before and after it

Replies are listed 'Best First'.
Re: find a specific word
by Anonymous Monk on Jul 04, 2013 at 09:11 UTC
Re: find a specific word
by flexvault (Monsignor) on Jul 04, 2013 at 11:31 UTC

    AM,

    From the Camel book (3rd edition), page 154:

    my $string = " \t DATA \t LIST \t \n"; ## my initializ +ation $string = join(" ", split " ", $string); ## From book
    Result: "DATA LIST" without CR.

    Regards...Ed

    "Well done is better than well said." - Benjamin Franklin

Re: find a specific word
by Laurent_R (Canon) on Jul 04, 2013 at 11:35 UTC

    Take a look at the following example under the Perl debugger:

    DB<15> @c = qw /jan feb mar apr may jun/ DB<16> for ( 0..$#c ) { print $_ if $c[$_] =~ /ay/ } 4
Re: find a specific word
by AnomalousMonk (Archbishop) on Jul 04, 2013 at 17:24 UTC
    ... find position [i.e., index] specific word like "DATA LIST" in an array , but ... it can have spaces before or after ... [emphasis added]

    Another approach. Searches for the words separated by one or more of any whitespace character; this could easily be refined to a single space. Be sure you understand   List::MoreUtils::indexes and regexes before you turn in your homework.

    >perl -wMstrict -le "use List::MoreUtils qw(indexes); ;; my @ra = ( 'DATA', 'LIST', 'DATALIST', 'FOO', ' DATALIST ', 'data list', 'DATA LIST', ' DATA LIST ' ); ;; my $search = qr{ DATA \s+ LIST }xms; ;; my @indices = indexes { $_ =~ $search } @ra; print qq{at index $_ found '$ra[$_]'} for @indices; " at index 6 found 'DATA LIST' at index 7 found ' DATA LIST '