Showing entries with tag "Array".

Found 12 entries

Perl: Add an element to the middle of an array

If you want to add an element to the middle of an existing array you can use the splice() function. Splice modifies arrays in place. Splice takes four arguments for this: the array to modify, the index of where you want to modify, the number of items you want to remove, and an array of the elements to add.

my @x = qw(one three);

# At the 2nd index, add (replace zero elements) a one element array
splice(@x, 1, 0, ('two'));

print join(" ", @x); # "one two three"
Leave A Reply

Perl: Get certain elements of an array the lazy way

I learned that you can extract various elements from a Perl array in a very creative/simple way. Using this syntax may simplify some of your code and save you a lot of time.

my @colors = ("red", "blue", "green", "yellow", "orange", "purple");

my @w = @colors[(0, 3)];    # ("red", "yellow");
my @x = @colors[(0, 2, 4)]; # ("red", "green", "orange");

# First and last element
my @y = @colors[(0, -1)];   # ("red", "purple");

# First ten items
my @z = @array[0 .. 10];    # Using the `..` range operator

Basically any call to an array where the payload is an array of indexes will return a new array with those items extracted.

my @colors = ("red", "blue", "green", "yellow", "orange", "purple");

# You can also use an array variable to specify the elements to extract
my @ids = (1,3,5);
my @x   = @colors[@ids]; # ("blue", "yellow", "purple")

Note: Since you are referencing the whole array (not one element) you use the @ sigil instead of $.

Leave A Reply

Python: Null coallesce on an array

I have a small array in Python, and I need to get the 2nd element of that array, or a default value if it's not present. All the other languages (PHP, Perl, Javascript) I use have a simple null coallescing operator that makes it simple, but not Python. I got tired of writing it out every time to so I wrote a simple wrapper function:

x = [2,4,6]

# Get the 3rd item from x
y = arrayItem(2, x, -1) # 6
# Get the 8th (non-existent) item from x
y = arrayItem(7, x, -1) # -1
# Get an item from an array, or a default value if the array isn't big enough
def arrayItem(needle, haystack, default = None):
    if needle > (len(haystack) - 1):
        return default
    else:
        return haystack[needle]

If there is a better, simpler, built-in way I'm open to hearing it.

Leave A Reply - 1 Reply

Perl: Remove an item from array

If you want to remove an item from an array you can use a inverse grep filter like this:

my @x = qw(foo bar baz orange);
@x    = grep { !/orange/ } @x;

or

my @x = qw(foo bar baz orange);
@x    = grep { $_ ne 'orange' } @x;
Leave A Reply

Perl: Find unique items in an array

I need to extract all the unique elements from an array. There is no built-in way to do this, but there are several user functions you can use.

my @x = qw(one two one three one four);
my @y = array_unique(@x); # ("one", "two", "three", "four")
# Borrowed from: https://perlmaven.com/unique-values-in-an-array-in-perl
sub array_unique {
    my %seen;
    return grep { !$seen{$_}++ } @_;
}

I stand corrected, List::Util includes a uniq() function to do exactly this, is a core module, and is included with all Perl installations.

Leave A Reply

Perl: Extract a column from a hashref

I have an array full of hash references and I need to extract a column and build an array from that.

my @x = ( {'ip' => '127.0.0.1'}, {'ip' => '10.10.10.10'}, {'ip' => '192.168.5.6'} );
my @y = hash_column('ip', @x); # ["127.0.0.1", "10.10.10.10", "192.168.5.6"]
sub hash_column {
    my $col = shift();
    my @arr = @_;

    my @ret;
    foreach my $x (@arr) {
        push(@ret, $x->{$col});
    }

    return @ret;
}
Leave A Reply

Perl: Find the longest string in an array

I need a Perl way to find the maximum string length in an array so here is a function to do that:

my @words = qw(Apple Pear Watermelon Banana Cherry);
my $max   = max_length(@words); # 10
sub max_length {
    my $max = 0;

    foreach my $item (@_) {
        my $len = length($item);
        if ($len > $max) {
            $max = $len;
        }
    }

    return $max;
}
Leave A Reply

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'));

print_r($new_arr);
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, @haystack) = @_;

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

    return 0;
}

Alternately you can use grep which in some cases can be faster:

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

    my $ret = grep { $_ eq $needle; } @haystack;

    return $ret;
}

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

Leave A Reply