1

I have an array like this:

my @array = qw( zero one two three four five six seven eigth nine);

How to output a subarray consisting of strings of length 4 from @array. For example, if the string is equal to 4, the new array will be output as @subarray = ( zero four five nine )

1 Answer 1

5

The built-in function grep serves as the "filter" operation in Perl, capable of filtering a list based on a regular expression or an arbitrary block.

If given a block, grep will call the block for each element of the list, setting the implicit variable $_ to the current value. It will keep the values which return truthy. So your filter would look like

my @subarray = grep { length == 4 } @array;

length, like a lot of built-in Perl functions, can take an argument (length($a), etc.), but when called without one it automatically takes the implicit variable $_ as an argument.

You can also pass it a regular expression. This is mainly useful if you're worried your coworkers like you too much and want to make some enemies.

my @subarray = grep(/^.{4}$/, @array);
Sign up to request clarification or add additional context in comments.

3 Comments

So length is like querying of what?
length with no argument uses $_as a default argument
@AnArrayOfFunctions See $_ in perlvar for a long list of things that take $_ as their default

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.