in reply to Re: prepend string to entire array
in thread prepend string to entire array

Sorry, but that's wrong.

Your code will only work if @array1 is (1..7). If it is, say, ('H'..'N'), it will return the wrong result.

Replies are listed 'Best First'.
Re: Re: Re: prepend string to entire array
by blue_cowdawg (Monsignor) on Sep 10, 2003 at 18:07 UTC

        Sorry, but that's wrong. Your code will only work if @array1 is (1..7). If it is, say, ('H'..'N'), it will return the wrong result.
    Two words: Problem Definition
    Based on what you stated as your orginal problem then what I proposed will work. However, given your refinement of your problem set:

    # # Arguments: # $a1 == reference to an array of scalars # $a2 == reference to an array of scalars # Returns: # an array of scalars that are the result of # prepending the contents of $a2 to the elements of $a1 # or undef if the number of elements of $a1 and $a2 # are not the same. sub prepender{ my ($a1,$a2)=@_; my @ax=@$a1; # Dereference only for clarity. my @ay=@$a2; # same as above return undef if $#ax != $#ay; return map { $ay[$_] . $ax[$_] } (0..$#ax); } # # Sample call my @array=('A'..'G'); my @array1=(10..($#array1+9)); my @array2=prepender(\@array,\@array1);
    This includes some basic error checking....


    Peter L. Berghold -- Unix Professional
    Peter at Berghold dot Net
       Dog trainer, dog agility exhibitor, brewer of fine Belgian style ales. Happiness is a warm, tired, contented dog curled up at your side and a good Belgian ale in your chalice.