in reply to Test if variable is equal to a bracket?

What do you mean by "doesn't work"? What, exactly, are you expecting?

Note that your join statement modifies $array[$i], but leaves $array[$i+1] and $array[$i+2] unaltered.

A word spoken in Mind will reach its own level, in the objective world, by its own weight

Replies are listed 'Best First'.
Re^2: Test if variable is equal to a bracket?
by mdunnbass (Monk) on May 16, 2007 at 22:10 UTC
    Good point. Here's what I'm expecting... If: @array = ('A','B','C','[','D',']','E','F'); The result I want would be:  'A','B','C','[D]','E','F' Instead, @array is left untouched.

    As for leaving $array[$i+1] and $array[$i+2] unaltered, I take care of them in the next line.

    Thanks though for the concern....
    Matt

      Hi mdunnbass,

      There's nothing wrong with your comparison if ($array[$i] eq '['); rather, I'm guessing it's a problem with the way you're iterating over the array, and trying to change it in-place.

      I would recommend you use a temporary array for this, as it's easier to process, and there's no chance of messing up the original:

      #!/usr/local/bin/perl use strict; use warnings; use Data::Dumper; my @array = ('A','B','C','[','D',']','E','F'); my @results = ( ); while (@array) { my $string = shift @array; if ($string eq '[' and @array > 2) { $string .= (join "", splice(@array, 0, 2)); } push @results, $string; } printf "Results => %s\n", Dumper(\@results);

      s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
        Thanks!

        I wound up using a slightly modified version of this, and it does the job perfectly.

        And thanks to everyone else for their advice.

        Matt

      This seems to work:
      use strict; my @array = qw/A B C [ D ] E F/; my @outarray; my $outid = 0; my $incrm = 1; for my $ch ( @array ) { $outarray[$outid] .= $ch; $incrm = ( $ch eq '[' ) ? 0 : ( $ch eq ']' ) ? 1 : $incrm; $outid += $incrm; } print "@outarray\n";