将分隔行的列表拆分为哈希

kob*_*ame 2 perl

以下产生我想要的东西.

#!/usr/bin/env perl
use 5.020;
use warnings;
use Data::Dumper;

sub command {
    <DATA>
    #in the reality instead of the DATA I have
    #qx(some weird shell command what produces output like in the DATA);

}
my @lines = grep { !/^\s*$/ } command();
chomp @lines;

my $data;

#how to write the following nicer - more compact, elegant, etc.. ;)
for my $line (@lines) {
    my @arr = split /:/, $line;
    $data->{$arr[0]}->{text} = $arr[1];
    $data->{$arr[0]}->{par} = $arr[2];
    $data->{$arr[0]}->{val} = $arr[3];
}
say Dumper $data;

__DATA__
line1:some text1:par1:val1
line2:some text2:par2:val2

line3:some text3:par3:val3
Run Code Online (Sandbox Code Playgroud)

想知道如何以更美观的形式编写循环.;)

cho*_*oba 5

您可以分配给哈希切片:

for my $line (@lines) {
    my ($id, @arr) = split /:/, $line;
    @{ $data->{$id} }{qw{ text par val }} = @arr;
}
Run Code Online (Sandbox Code Playgroud)

另外,使用以下代码qx,因此您不需要将所有行存储在数组中:

open my $PIPE, '-|', 'command' or die $!;
while (<$PIPE>) {
    # ...
}
Run Code Online (Sandbox Code Playgroud)