获取匹配括号的索引

Amm*_*ema 3 arrays perl parentheses

嗨,我正在尝试打印以下括号模式的索引:

((((((...)))(((...))))))
Run Code Online (Sandbox Code Playgroud)

如下:

0 23
1 22
2 21
3 11
4 10
5 9
12 20
13 19
14 18
Run Code Online (Sandbox Code Playgroud)

我尝试使用下面给出的此perl代码来实现此目的:

#!/usr/bin/perl
use strict;
use warnings;

my $string = '((((((...)))(((...))))))';
my @myarray = split('', $string); 
my @stack;
my @stack1;



while (my ($index, $element) = each(@myarray))
{

   if ($element eq '(')
   {
   push(@stack, $index);  
   }

   if ($element eq ')')
   {
   push(@stack1, $index);  
   }  
}


print "$stack[$_]-$stack1[$_]\n" for (0 .. $#stack);
Run Code Online (Sandbox Code Playgroud)

但是上面的代码给了我以下输出,这不是必需的输出:

0-9
1-10
2-11
3-18
4-19
5-20
12-21
13-22
14-23
Run Code Online (Sandbox Code Playgroud)

有什么办法可以实现?

cho*_*oba 6

推入左侧括号中的堆栈,在右侧弹出。

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my $string = '((((((...)))(((...))))))';

my @output;
my @stack;

my $pos = 0;
for my $char (split //, $string) {
    if ($char eq '(') {
        push @stack, $pos;
    } elsif ($char eq ')') {
        push @output, [ pop @stack, $pos ];
    }
    ++$pos;
}
say "@$_" for sort { $a->[0] <=> $b->[0] } @output;
Run Code Online (Sandbox Code Playgroud)