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

I'm trying to iterate through an array, and I have a string that I need to append a number to each iteration.
i.e. #!/usr/bin/perl use strict; my @array = qw(TEST); my $num = 1; foreach (@array) { $_ .= ($num +=1); }
Instead of the number increasing (TEST1, TEST2, TEST3) it's appending the number (TEST1 TEST11 TEST111)
Any ideas?

Replies are listed 'Best First'.
Re: A simple question regarding join
by jasonk (Parson) on Feb 19, 2003 at 21:37 UTC

    Your problem code is doing something that this sample code is not, because this sample code behaves as you expect.

    #!/usr/bin/perl -w use strict; my @array = qw(TEST TEST TEST); my $num = 1; foreach (@array) { $_ .= ($num +=1); } print join(" ",@array)."\n"; # produces: TEST2 TEST3 TEST4
Re: A simple question regarding join
by Limbic~Region (Chancellor) on Feb 19, 2003 at 21:50 UTC
    What you wrote (aside from your code) doesn't make sense to me, but let me give it a shot.
    It sounds like you have an array of scalar strings and you want to append a increasing number to the string - almost like making the array index part of the value.
    If that is the case, try this:

    #!/usr/bin/perl -w use strict; my @array = qw(john jacob jingle heimer smitz); my $index = 0; foreach (@array) { $_ .= $index; $index++; } print "My new array looks like\n"; print "$_\n" foreach (@array);

    If this isn't what you were trying to do - please explain further.

    Hope this helps - cheers - L~R

Re: A simple question regarding join
by bart (Canon) on Feb 20, 2003 at 02:06 UTC
    Can't be. You must be testing in some other language than Perl, because in Perl, + and += are for arithmetic calculations only, not for string concatenation.
Re: A simple question regarding join
by physi (Friar) on Feb 19, 2003 at 23:28 UTC
    use strict; my $i=1; @array = map{$_ . $i++} qw(TEST TEST TEST); print "@a";
    -----------------------------------
    --the good, the bad and the physi--
    -----------------------------------
    
      physi,

      Your code doesn't compile, might I suggest:

      use strict; my $i=1; my @array = map{$_ . $i++} qw(TEST TEST TEST); print "@array";

      Cheers - L~R

        Yupp you're right, It was just 'out-of-the-head' and maybe it's to late in the evening ;-)
        -----------------------------------
        --the good, the bad and the physi--
        -----------------------------------
        
Re: A simple question regarding join
by steves (Curate) on Feb 19, 2003 at 21:39 UTC

    I don't think so. You should run that again. My mental code executer tells me you get one array element when done named TEST2.