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

Dear Masters,

How can I modify my code below. Such that given $tpl, I can remove the recurring consecutive alphabet,
B-B into just B, and A-A into just A?

Is there a better way to implement it?
Also could it be made faster?
My current wrong answer and the intended result is shown below.
Update: Typo corrected. Thanks to skillet-thief .
use Data::Dumper; my $tpl = ['A -4 B','B -4 C','C -4 A','A -4 B']; get_alphb_fr_tpl($tpl); sub get_alphb_fr_tpl { my $aref = shift; my @str = grep (!/[\d+\s+]/,map{ split " ",$_} @{$aref}) ; print Dumper \@str ; return; }
Such that it gives:
$VAR1 = ['A','B','C','A','B'];
Instead of:
$VAR1 = ['A','B','B','C','C','A','A','B'];


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

Replies are listed 'Best First'.
Re: Removing recurring consecutive element
by Skeeve (Parson) on Oct 13, 2005 at 07:06 UTC

    Hmmm... Sure you want to delete consecutive same elements? To me it seems you want the first word of each string.

    If so what about:

    my @str = map{ (split ' ', $_, 2)[0] } @{$tpl} ;

    instead of your grep-line

    This way you get the first element of each of your strings.


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
      To me it seems you want the first word of each string.
      No Skeeve. That's not what I want. Instead of this:
      $VAR1 = ['A','B','C','A'];
      I am looking for this:
      $VAR1 = ['A','B','C','A','B'];
      So you can see. For the last array I want to keep the 'last word', which is B. I hope that's clearer for you now.

      ---
      neversaint and everlastingly indebted.......
        If that's what you want. Add this one line after Skeeve's.
        push @str, (split ' ',$tpl->[-1])[2];
        Sorry I still don't know if this implementation gives the fastest running time.

        Regards,
        Edward
Re: Removing recurring consecutive element
by neosamuri (Friar) on Oct 13, 2005 at 07:20 UTC
    You could do something like this:
    sub get_alphb_fr_tpl { my $aref = shift; my @str = grep (!/[\d+\s+]/,map{ split " ",$_} @{$tpl}) ; my $lst = ''; my @out; for(@str){ $out[@out] = $_ unless $lst eq $_; $lst = $_; } print Dumper \@out ; return; }
    I am sure that there is a more elegant way of doing it, but this works.
Re: Removing recurring consecutive element
by skillet-thief (Friar) on Oct 13, 2005 at 07:30 UTC

    I assume it is a typo, but you are not using the $aref that you are passing to the sub, and instead working directly on $tpl.

    s-t


    sub sk{ return unless $in = shift; $in =~ s!(.)$!!; print $1; sk($in)} sk("gro.alubaf@yehaf");
Re: Removing recurring consecutive element
by Perl Mouse (Chaplain) on Oct 13, 2005 at 08:53 UTC