perl匹配2d数组中的字符串

时间:2017-08-08 05:02:58

标签: arrays perl

需要匹配2D数组中的字符串并列出坐标。 例如。 在下面的数组中,我需要确定每行和每列 var clickedFrameID=""; //This is a Global Variable browser.contextMenus.create({ "title": "Records", "contexts": ["all","link"], "id" : "M1", "onclick": onClickContextMenu, }, function() { }); function onClickContextMenu(info, tab){ var options={}; if(clickedFrameID !="" && clickedFrameID!=null && clickedFrameID!=undefined ) { options={ file: "fileName.js", allFrames: false, frameId: clickedFrameID }; } browser.tabs.executeScript(tab.id,options, function() { console.log("Script injected"); }); } 的位置。为简单起见,假设每个行和列只有一个'*'元素。

'*'

预期结果将是

my @array = (
  [qw(* - -  - - -  - - -)],  #1
  [qw(- - -  * - -  - - -)],  #2
  [qw(- - -  - - -  * - -)],  #3

  [qw(- * -  - - -  - - -)],  #4
  [qw(- - -  - * -  - - -)],  #5
  [qw(- - -  - - -  - * -)],  #6

  [qw(- - *  - - -  - - -)],  #7
  [qw(- - -  - - *  - - -)],  #8
  [qw(- - -  - - -  - - *)],  #9
);

此示例具有对称数组,但并非所有矩阵都必然会出现。

2 个答案:

答案 0 :(得分:1)

一种方法:使用线性索引识别元素的位置,然后从

重建行/列
use warnings;
use strict;
use feature 'say';

use List::MoreUtils qw(indexes);

my @matrix = ( ... );  # from the question

my @linear_idx = indexes { $_ eq '*' } map { @$_ } @matrix;

# Compute (row,col) points from linear indices (rectangular matrix)
my @pts = do {
    my $num_cols = @{$matrix[0]};
    map {
        my $row = int $_/$num_cols;
        [ $row + 1, $_ - $row*$num_cols + 1 ] 
    } @linear_idx;  
};

say "rows: ", join ',', map { $_->[0] } @pts;
say "cols: ", join ',', map { $_->[1] } @pts; 

打印

rows: 1,2,3,4,5,6,7,8,9
cols: 1,4,7,2,5,8,3,6,9

答案 1 :(得分:0)

检查以下

String s = "Hello";
String s2 = new String("Hello");
s2.intern();
System.out.println(s == s2);