Perl Scripts ·

Perl Arrays: Length, Add, Remove and Check for a Value

By Manu Mathew, Technical Lead Engineer · Published 14 January 2014 · Last updated 5 October 2026

Isometric illustration of a row of blocks, one being added and one removed, with a blue magnifier over a block

Coming to Perl from PHP, one of the first things people look for is in_array(). Perl has no function with that name, but it has several good ways to do the same job. This page brings together several short notes on Perl arrays I wrote between 2013 and 2016. I have rewritten them in one place, with tested examples and current advice, so you don’t have to piece the answer together from fragments.

Quick answer

scalar(@array) gives the length and $#array the last index. push and pop work at the end, unshift and shift at the start. To check for a value, use any { $_ eq $x } @array from List::Util, or a hash for many lookups. Use grep to find matches.

I tested each example with Perl 5.40, using use strict and use warnings.

How do I get the length of an array?

Use the array in scalar context, for example scalar(@array); $#array is the last index, one less than the length.

use strict;
use warnings;

my @coins = ('Quarter', 'Dime', 'Nickel');
my $count = @coins;            # an array in scalar context gives its length
print "Count: $count\n";               # Count: 3
print "Count: ", scalar(@coins), "\n"; # Count: 3
print "Last index: $#coins\n";         # Last index: 2

If you assign to an index far past the end, the array grows to fit, with undef in between: after $coins[50] = 'Rupee' the length is 51.

How do I add or remove elements at either end?

push and pop work on the end of the array, unshift and shift on the start, and splice anywhere in the middle.

use strict;
use warnings;

my @coins = ('Quarter', 'Dime', 'Nickel');

push @coins, 'Penny';          # add to the end
unshift @coins, 'Dollar';      # add to the start
print "@coins\n";              # Dollar Quarter Dime Nickel Penny

my $last  = pop @coins;        # remove from the end   (Penny)
my $first = shift @coins;      # remove from the start (Dollar)
print "@coins\n";              # Quarter Dime Nickel

splice @coins, 1, 1;           # remove one element at index 1 (Dime)
print "@coins\n";              # Quarter Nickel
FunctionWhereReturns
push @a, $xAdds to the endThe new length
pop @aRemoves from the endThe removed element
unshift @a, $xAdds to the startThe new length
shift @aRemoves from the startThe removed element
splice @a, $i, $nRemoves $n elements at index $iThe removed elements

How do I check whether an array contains a value?

Use any from List::Util for a single check, and build a hash once if you will check many values against the same list.

use strict;
use warnings;
use List::Util qw(any);

my @names = ('Manu', 'Vinu', 'Rinshad');

# One check: List::Util's any stops at the first match
if (any { $_ eq 'Manu' } @names) {
    print "Manu is in the list\n";
}

# Many checks against the same list: build a hash once
my %is_name = map { $_ => 1 } @names;
for my $who ('Vinu', 'Amal') {
    print $is_name{$who} ? "$who: yes\n" : "$who: no\n";
}

any stops at the first match and has been in List::Util, a core module, since Perl 5.20. Use eq for strings and == for numbers.

A small in_array helper

If you prefer a PHP-style name, a short subroutine does the same thing:

use strict;
use warnings;

# A small in_array helper, like PHP's in_array()
sub in_array {
    my ($array_ref, $wanted) = @_;
    for my $item (@$array_ref) {
        return 1 if defined $item && $item eq $wanted;
    }
    return 0;
}

my @names = ('Manu', 'Vinu', 'Rinshad');
print in_array(\@names, 'Rinshad') ? "found\n" : "not found\n";   # found
print in_array(\@names, 'Manu ')   ? "found\n" : "not found\n";   # not found (trailing space)

The comparison is exact, so 'Manu ' with a trailing space is not found. That is usually what you want, but trim user input before checking.

Should I use the smartmatch operator (~~) for this?

No, not in new code. Smartmatch ($x ~~ @array) was experimental from Perl 5.18, deprecated in 5.38, and in 5.42 it is kept only for old code and is switched off by use v5.42.

An older note on this site suggested use experimental 'smartmatch' to silence the warnings. That still works on older versions, but any or a hash lookup is clearer and works on every Perl version.

How do I find every element that matches a pattern?

grep returns the matching elements in list context, and the number of matches in scalar context.

use strict;
use warnings;

my @words   = ('Hai', 'Leop', 'mac');
my @with_a  = grep { /a/i } @words;        # every element containing "a" or "A"
print join(',', @with_a), "\n";            # Hai,mac

my $matches = grep { /a/i } @words;        # in scalar context: how many matched
print "$matches matched\n";                # 2 matched

How do I check whether a value is an array reference?

ref($value) eq 'ARRAY' is true for an unblessed array reference.

use strict;
use warnings;

sub is_array_ref {
    my ($value) = @_;
    return ref($value) eq 'ARRAY';
}

my $data = { codes => [12001, 25000], single => 1000 };
for my $key (sort keys %$data) {
    my @codes = is_array_ref($data->{$key}) ? @{ $data->{$key} } : ($data->{$key});
    print "$key: @codes\n";
}
# codes: 12001 25000
# single: 1000

This is common with data parsed from XML or JSON, where a field may hold one value or a list. For objects built on arrays, reftype from Scalar::Util returns ARRAY even when ref returns the class name.

Need help? If your Perl array code is part of an older application that needs fixing or updating, I can take a look. See Perl development, or email manu@manu.co.in.

Frequently asked questions

How do I remove duplicate values from an array?

Use uniq from List::Util, which keeps the first copy of each value in the original order. On older Perl versions, a %seen hash with grep does the same job. Removing duplicate values from a Perl array covers both, including case-insensitive matching.

How do I find the position of a value in an array?

Loop over the indexes and keep the first match: my ($i) = grep { $array[$_] eq $wanted } 0 .. $#array;. The result is undef when the value isn’t there, so check it before you use it. List::MoreUtils from CPAN also offers firstidx.

How do I remove an element by value rather than by position?

Keep everything except that value with grep: @array = grep { $_ ne 'old' } @array;. This removes every copy of the value. To remove only the first copy, find its index first and pass it to splice.

How do I join an array into a string, or split it back?

Use join with a separator: join(', ', @names) gives “Asha, Ravi, Joe”. To turn a string back into an array, use split with a pattern, such as split /,\s*/, $text, which also drops the spaces after each comma.

Related notes: removing duplicate values from a Perl array; sorting arrays in Perl; multidimensional arrays in Perl; hiring a remote Perl developer.

Need help with Perl code?

If you have Perl code that needs fixing, extending or upgrading, I’m happy to take a look. I work remotely from Kozhikode, Kerala, with teams across India and elsewhere; Perl development and maintenance explains how I help. If you are deciding how to bring someone in, Hiring a remote Perl developer is a short checklist.

You can reach me through the contact section or email me at manu@manu.co.in. A few lines about the system and what you need is a good start.

Sources: perlfunc: push, pop, shift, unshift, splice; List::Util: any; perlfaq4: how can I tell whether a list contains an element?; perl5420delta: smartmatch kept behind a feature; perlfunc: ref.

Back to the blog