0

我仍在学习如何使用 map 命令,并且无法弄清楚如何将以下代码从以下代码转换为使用 map 命令:

单线

perl -MData::Dumper -wE'
   $_ = "Alpha,Beta,Gamma|Alpha,Beta";
   say;
   ($first,$second)=split/\|/;
   @first=split /,/,$first;
   @second=split /,/, $second;
   print Dumper({FIRST=>\@first, SECOND=>\@second})
'

完整脚本:

#! /usr/bin/perl  
use strict; 
use warnings; 
use Data::Dumper;
use v5.10; 

$_ = "Alpha,Beta,Gamma|Alpha,Beta";

say;

my ($first,$second)=split/\|/; 
my @first=split /,/,$first; 
my @second=split /,/, $second; 
warn Dumper({FIRST=>\@first, SECOND=>\@second});

我希望使用 map 函数将下面的行转换为两个数组:

阿尔法,贝塔,伽玛|阿尔法,贝塔

$VAR1 = {
          'FIRST' => [
                       'Alpha',
                       'Beta',
                       'Gamma'
                     ],
          'SECOND' => [
                        'Alpha',
                        'Beta'
                      ]
        };
4

2 回答 2

4

重复的部分是逗号拆分、数组的创建、分配给该数组并获取对该数组的引用(my @first = split /,/, $first; \@first),所以这就是循环内部的内容(my @a = split /,/, $_; \@a又名[ split /,/ ])。

my %h; @h{qw( FIRST SECOND )} = map [ split /,/ ], split /\|/;

购买为什么要使用哈希?数组会更自然。

my @a = map [ split /,/ ], split /\|/;

对于后者,您将使用$a[0]and$a[1]而不是$h{FIRST}and $h{SECOND}

于 2013-11-02T17:24:04.377 回答
3
perl -MData::Dumper -wle'
  $_ = "Alpha,Beta,Gamma|Alpha,Beta"; 
  print;
  my @r = 
      # map { my @x = split /,/; \@x } 
      map { [split /,/] } # same functionality as above
      split/\|/; 
  warn Dumper \@r;
'

和上面的精确输出(Dumper href)

perl -MData::Dumper -wle'
  $_ = "Alpha,Beta,Gamma|Alpha,Beta"; 
  print;
  my %h =
      map { qw(FIRST SECOND)[$i++] => [split /,/] }
      split/\|/; 
  warn Dumper \%h;
'
于 2013-11-02T17:04:52.353 回答