Showing entries with tag "Array".

Found 5 entries

Perl: array_chunk() to split arrays into smaller chunks

I have an large array in Perl that I need in smaller chunks to make iteration easier. I borrowed a concept from PHP and implemented array_chunk() in Perl.

my @orig = qw(foo bar baz one two three red yellow green donk);
my @new  = array_chunk(3, @orig);
sub array_chunk {
    my ($num, @arr) = @_;
    my @ret;

    while (@arr) {
        push(@ret, [splice @arr, 0, $num]);

    return @ret;
Leave A Reply

Perl: find the index of an array item

I needed to find the index of an item in an array so I wrote a simple Perl function.

my @arr = qw(foo bar baz donk);
my $x   = array_index("bar", @arr)); # 1
sub array_index {
    my ($needle, @haystack) = @_;

    if (defined($needle)) {
        for (my $idx = 0; $idx < @haystack; $idx++) {
            if ($haystack[$idx] eq $needle) {
                return $idx;

    return undef;
Leave A Reply - 1 Reply

Perl: doing a regexp replace on an array

I have an array of items that I want to do a quick regexp replace on each element. Here is a very elegant solution:

@names = ("John", "Paul", "george", "Ringo");
s/^g/G/g for @names;
print join(", ",@names);
Leave A Reply

Remove an item from a PHP array

Given an array in PHP, I need to remove a specific element (if it exists in the array) from the array. The following is a pretty simple and elegant solution. I didn't use unset on purpose because you have to check for a integer result before you remove the item from the array.

$arr     = array('apple','banana','orange');
$new_arr = array_diff($arr, array('banana'));

Leave A Reply

Perlfunc: in_array()

If you need to determine if an array contains a specific element you can use this function:

sub in_array {
    my $needle   = shift();
    my @haystack = @_;

    foreach my $l (@haystack) {
        if ($l eq $needle) { return 1; }

    return 0;

Note: If you want to check integers just change the eq to ==

Leave A Reply