我还在学习如何使用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'
]
};
答案 0 :(得分:4)
重复的部分是逗号分割,数组的创建,分配给该数组并获取对该数组的引用(my @first = split /,/, $first; \@first
),所以这就是循环内部的内容({{ 1}}又名my @a = split /,/, $_; \@a
)。
[ split /,/ ]
购买你为什么使用哈希?阵列会更自然。
my %h; @h{qw( FIRST SECOND )} = map [ split /,/ ], split /\|/;
使用后者,您可以使用my @a = map [ split /,/ ], split /\|/;
和$a[0]
代替$a[1]
和$h{FIRST}
。
答案 1 :(得分: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;
'