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

I'm trying to find a way to concatentate subsequent array elements into a new array upon matching a string walking an array. For example:
#!/usr/bin/perl my $file = '/output.txt'; open DATA, "$file" or die "can't open file"; my @array = <DATA>; for($i=1; $i < 10; $i++) { foreach my $found ($array[$i]) { if ( $found =~ /string1/ ) { my @new = join($array[$i], $array[$i++]); } } } close (DATA);
Let's say "string1" is $array[2] now I want to be able to create a @new with $array[2] and $array[3] concatentated. I'm guessing I'd use join somehow (ie, my @new = join($array[$i], $array[$i+1];), but am having problems figuring out how to do $array[$?] + 1 element when I don't know statically what the matching array element number is.

Anybody have any idea's?

Thanks,

Jim

Replies are listed 'Best First'.
Re: array element question
by jdporter (Paladin) on Nov 21, 2006 at 23:16 UTC

    In situations like this, I find it a little more natural to shift off the elements, rather than iterate using a counter. But it means you have to take measures to keep from destroying the source, if that would matter. Putting it all in a subroutine can provide this measure of safety.

    sub foo # not sure what you'd call this { my $pat = shift; my @r; while (@_) { my $x = shift; push @r, $x; $x =~ /$pat/ and $r[-1] .= shift; } @r } my @new = foo( qr/string1/, @array );
    We're building the house of the future together.
Re: array element question
by chromatic (Archbishop) on Nov 22, 2006 at 02:13 UTC
    my @new = join($array[$i], $array[$i++]);

    Be very careful with that. Who knows when the ++ will happen in relation to the array accesses! (I think you can guarantee that it will happen before the second one, but how about in relation to the other?

      probably best not to use assignments in array access. You'll need another line of code to do the increment, but I think it's worth it.

      How can you feel when you're made of steel? I am made of steel. I am the Robot Tourist.
      Robot Tourist, by Ten Benson

Re: array element question ($prev)
by tye (Sage) on Nov 21, 2006 at 23:53 UTC
    my @new; my $prev= ''; my $found= 0; while( <DATA> ) { if( $found ) { push @new, $prev . $_; } $found= /string1/; $prev= $_; }

    - tye        

      Thanks for all the responses!!
Re: array element question
by GrandFather (Saint) on Nov 21, 2006 at 23:24 UTC

    If you don't mind clobbering the array or copying it to a temporay version then you can:

    use strict; use warnings; my @array = <DATA>; chomp @array; for my $index (0 .. $#array) { next unless $array[$index] =~ /'/ && exists $array[$index + 1]; $array[$index] .= $array[$index + 1]; $array[$index + 1] = ''; } @array = grep {length} @array; print join "\n", @array; __DATA__ I' m guessing I' d use join somehow

    Prints:

    I'm guessing I'd use join somehow

    DWIM is Perl's answer to Gödel