【问题标题】:how do i put array elements from one array into another in perl?perl 如何将数组元素从一个数组放入另一个数组?
【发布时间】:2012-08-31 17:52:15
【问题描述】:

如果我有一个带有行的@array:

row 1: a   b

row 2: b   c

row 3: c   d

我如何获得一个新的@array2,将所有元素放在一列中,所以@array2 = a b b c c d?

谢谢!

【问题讨论】:

    标签: arrays perl foreach while-loop two-columns


    【解决方案1】:

    您的问题措辞有些含糊,这可能是因为您是 perl 新手。您没有以 perl 语法提供您的输入或预期输出,但根据您对先前答案的回复,我会猜测一下:

    ##  three rows of data, with items separated by spaces
    my @input = ( 'a b', 'b c', 'c d' );
    
    ## six rows, one column of expected output
    my @expected_output = ( 'a', 'b', 'b', 'c', 'c', 'd' );
    

    将此作为您预期的输入和输出,编码转换的一种方法是:

    ##  create an array to store the output of the transformation
    my @output;
    
    ##  loop over each row of input, separating each item by a single space character
    foreach my $line ( @input ) {
        my @items = split m/ /, $line; 
        push @output, @items;
    }
    
    ##  print the contents of the output array
    ##    with surrounding bracket characters
    foreach my $item ( @output ) {
        print "<$item>\n";
    }
    

    有关 split 和 push 的更多信息,请参阅 perldoc。

    【讨论】:

    • 谢谢!很酷的代码!我想我发现了我的问题 - 我的 while 循环意味着在处理结束时只有一个元素,并且我以错误的方式使用了 push,自修复以来,它已经解决了!
    【解决方案2】:
    my @array_one = (1, 3, 5, 7);
    my @array_two = (2, 4, 6, 8);
    
    my @new_array = (@array_one, @array_two);
    

    【讨论】:

    • 我不考虑组合数组 - 我想获取数组中的元素,而不是将“a b”作为第 1 行中的元素,我希望将“a”作为第 1 行中的元素,后跟“b”作为array2的第2行中的元素
    【解决方案3】:

    这是另一个选择:

    use Modern::Perl;
    
    my @array = ( 'a b', 'b c', 'c d' );
    my @array2 = map /\S+/g, @array;
    
    say for @array2;
    

    输出:

    a
    b
    b
    c
    c
    d
    

    map 对@array 中的列表进行操作,将正则表达式(匹配非空白字符)应用于其中的每个元素以生成放入@array2 的新列表。

    【讨论】:

      【解决方案4】:

      您的初始数据的另一种可能解释是您有一个数组引用数组。这个“看起来”像一个二维数组,因此你会谈论“行”。如果是这种情况,那么试试这个

       #!/usr/bin/env perl
      
      use warnings;
      use strict;
      
      my @array1 = (
        ['a', 'b'],
        ['b', 'c'],
        ['c', 'd'],
      );
      
      # "flatten" the nested data structure by one level
      my @array2 = map { @$_ } @array1;
      
      # see that the result is correct
      use Data::Dumper;
      print Dumper \@array2;
      

      【讨论】:

        猜你喜欢
        • 2012-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多