Home > Enterprise >  Output elements in array using perl
Output elements in array using perl

Time:11-02

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 )

CodePudding user response:

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);
  •  Tags:  
  • perl
  • Related