in reply to prepend string to entire array

Try this:

@array = qw (A B C D E F G); @array2 = map { sprintf("%s%d",$array[$_],$_+1) } (0..$#array);

Update:Corrected a mistake in my original code after actually shudder testing it.


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.

Replies are listed 'Best First'.
Re: Re: prepend string to entire array
by Anonymous Monk on Sep 10, 2003 at 16:32 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.

          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.