in reply to adding null values to the start of an array

Just set an element at the end of the array that you want to be undef. Perl fills in the gaps with undefs automatically.

#! /usr/bin/perl -w
#
use strict;
use warnings;

use Data::Dumper;
my @array;

$array[5] = undef; 
print Dumper( \@array );
Yields

$VAR1 = [
          undef,
          ${\$VAR1->[0]},
          ${\$VAR1->[0]},
          ${\$VAR1->[0]},
          ${\$VAR1->[0]},
          undef
        ];

Where ${\$VAR1->[0]} is a reference to the first element which is undef.

Inman

Replies are listed 'Best First'.
Re: Re: adding null values to the start of an array
by etcshadow (Priest) on Oct 08, 2003 at 15:22 UTC
    Right... only the guy asked for adding undefs to the head of the array, not the tail. Specifically, adding one undef to the front of array1 for every item in array2.
    unshift(@array1,(undef) x @array2);
    I don't know why its so commonplace to make things so complicated when someone asks a simple question around here.

    ------------
    :Wq
    Not an editor command: Wq
      Yeah!   ;-)   But in the spirit of TMTOWTDI-simply,
      splice(@array1,0,0, (undef) x @array2 );
      I have no idea which would be faster.
        I'm not positive, but it's my impression that push, pop, shift, and unshift are all implemented as either thin wrappers around splice or thin wrappers around whatever underlies splice. So I think that the most possible difference is a single stack-frame (call unshift, and then unshift calls splice, as opposed to calling splice directly)... but I'm not even sure that that isn't optimized away (as, like, a macro or some such in the underlying C code). To know for sure, I'd have to dig through the C source for the perl core, which I don't really feel like doing right now. ;-)

        ------------
        :Wq
        Not an editor command: Wq