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

Dear Masters,
With code below I intend to concatenate the array ($aref1 and $aref2) sequentially and intercepted with certain values in between.
use Data::Dumper; $Data::Dumper::Indent = 0; my $aref1 = [ 'D 4', 'E 6' ]; my $aref2 = [ 'A 0', 'B 1', 'C 2', 'A 3', 'B 4' ]; my $slen = 5; concat($aref1,$slen); # This already give correct result concat($aref2,$slen); # This still incorrect sub concat { my ($aref,$slen)= @_; my @concat; foreach my $i ( 1 .. $#{$aref} ) { my @out = split (" ", $aref->[$i-1]); my @in = split (" ", $aref->[$i]); # value to be put in (intercepted) my $val = $in[1]-$out[1]-$slen; push @concat, ($out[0],$val,$in[0]); } print Dumper \@concat ; return ; }

Currently, only $aref2 still gives incorrect result as follows:
$VAR1 = ['A',-4,'B','B',-4,'C','C',-4,'A','A',-4,'B'];
As you can see, the result above still contain the 'redundant' elements like B-B, C-C, A-A.
How can I change my code above so that it gives the following correct expected results:
$VAR1 = ['D',-3,'E']; # from $aref1 $VAR1 = ['A',-4,'B',-4,'C',-4,'A',-4,'B']; # from $aref2


---
neversaint and everlastingly indebted.......

Replies are listed 'Best First'.
Re: Concatenating Non-Redundant Elements into an Array
by Perl Mouse (Chaplain) on Oct 12, 2005 at 09:24 UTC
    By not pushing $in[0] on the @concat array. And to add an extra push after the loop:
    sub concat { my ($aref,$slen)= @_; my @concat; foreach my $i ( 1 .. $#{$aref} ) { my @out = split (" ", $aref->[$i-1]); my @in = split (" ", $aref->[$i]); # value to be put in (intercepted) my $val = $in[1]-$out[1]-$slen; push @concat, ($out[0],$val); } push @concat, ($aref->[-1]=~/\S+/g)[0]; print Dumper \@concat ; return ; }
    Perl --((8:>*