Satyasheel
Satyasheel

Reputation: 90

Why grep doesn't work on lists in perl

In Perl,

my @lista = ['THE', 'KITE', 'RUNNER'];
my @listb = grep { $_ ne 'KITE' } @lista;
print "" . Data::Dumper->Dump(\@listb);

prints nothing while

my @lista = ('THE', 'KITE', 'RUNNER');
my @listb = grep { $_ ne 'KITE' } @lista;
print "" . Data::Dumper->Dump(\@listb);

prints an array containing 'THE' 'RUNNER'.

Why grep doesn't work when array is defined within []?

How to do grep operations on an array defined in []?

Upvotes: 2

Views: 136

Answers (2)

Kamal Nayan
Kamal Nayan

Reputation: 1940

grep works on array, but [] returns an arrayref. To use an array, use () instead.
Here are two alternates to your program:

use Data::Dumper;
my $lista = ['THE', 'KITE', 'RUNNER'];
my @listb = grep { $_ ne 'KITE' } @$lista;
print Dumper \@listb;

OR

use Data::Dumper;
my @lista = ('THE', 'KITE', 'RUNNER'); 
my @listb = grep { $_ ne 'KITE' } @lista;
print Dumper \@listb;

Upvotes: 0

ikegami
ikegami

Reputation: 385764

[] doesn't return an array; it returns a reference to an array. A such, @lista only contains one element. You are comparing the stringification of that reference (something like ARRAY(0x61dc18)) with KITE. Seeing as those two strings are completely different, grep returns the reference and you store it in @listb.

I think you want the following:

my $array_a = ['THE', 'KITE', 'RUNNER'];
my @array_b = grep { $_ ne 'KITE' } @$array_a;
print Data::Dumper->Dump(\@array_b);

Upvotes: 11

Related Questions