Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks - how can i add a certain number of null values to the start of an array? e.g. say I count the number of elements in one array and want to add this number of null elements to the beggining of a second array?

I hope someone can help - can't find information on this anywhere

  • Comment on adding null values to the start of an array

Replies are listed 'Best First'.
Re: adding null values to the start of an array
by liz (Monsignor) on Oct 08, 2003 at 14:11 UTC
Re: adding null values to the start of an array
by LTjake (Prior) on Oct 08, 2003 at 14:13 UTC

    use unshift to add items to the start of an array.

    If by "null" you mean undef, then try this:

    use Data::Dumper; my @array1 = qw( 1 2 3 ); my @array2 = qw( 4 ); unshift @array2, undef for @array1; print Dumper( \@array2 );

    output:

    $VAR1 = [ undef, undef, undef, '4' ];

    --
    "To err is human, but to really foul things up you need a computer." --Paul Ehrlich

Re: adding null values to the start of an array
by broquaint (Abbot) on Oct 08, 2003 at 14:16 UTC
    use Data::Dumper; my @words = qw/ this Should produce Three null Values /; my @nulls = qw/ some stuff here /; unshift @nulls, (undef) x grep /^[A-Z]/, @words; print Dumper \@nulls; __ouytput__ $VAR1 = [ undef, undef, undef, 'some', 'stuff', 'here' ];
    There, we unshift the same number of undefs as there are words beginning with uppercase letters from @words on to the beginning of @nulls.
    HTH

    _________
    broquaint

Re: adding null values to the start of an array
by inman (Curate) on Oct 08, 2003 at 14:28 UTC
    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

      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.