0

I have a substring that I want to find within an array. How do I print all the matching substrings?

My code is like this:

@ar = <DATA>;
@skm = grep{m/SLP/g} @ar;
print "@skm\n";
__DATA__
VEFGSLPPKKKLVESLPMMK

I expected output is

SLP
SLP

In the scalar i can do it by using the $&, but I am confused about how to do it in an array. How can i do it?

2 Answers 2

3

grep only checks if element from list matched. You might want to use map to actually transform list element to what you need, in this case using regex to capture and return transformed list for each element from @ar array,

my @skm = map {m/(SLP)/g} @ar;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @mpapec. Special variable are not in array? Like $&
@Hussain no, grep only returns list element if condition evaluates to true.
@Hussain, grep has nothing to do with regex matches (e.g. my @bad = grep { $_ > $max } @nums;), so $& has nothing to do with grep.
1

The grep operator simply returns the subset of the input list where the expression in the first parameter evaluates to a true value.

Since your @ar array has only a single element, and because that element contains SLP, your call of grep returns it to you.

It sounds like what you need is map, which returns the result of the expression in the first parameter when executes in list context. The expression /SLP/g returns all occurrences of SLP in a string, so

map /SLP/g, <DATA>

will return a list of all occurrences on SLP in any line in the DATA file handle.

It is a little more complex if you want all possibly overlapping occurrences of a string, but it can be written using a more elaborate Perl regex. This program prints all overlapping occurrences of XXX from within XXXXXX. There are four instances because the pattern can be found starting at the first, second, third, and fourth characters of the target string.

use strict;
use warnings;
use 5.010;

say for map /(?=(XXX))/g, <DATA>

__DATA__
XXXXXX

output

XXX
XXX
XXX
XXX

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.