perl的丢弃在地图操作第一个数组元素 [英] perl discard first array element in map operation

查看:159
本文介绍了perl的丢弃在地图操作第一个数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始利用Perl的地图的能力,并遇到了,我无法找到答案的一个问题。基本上我解析它有一个标题行,我不需要,然后2的每件信息行UNIX命令的返回。目前,我这样做:

I'm starting to harness the power of perl map, and have run into a question that I couldn't find an answer to. Basically I am parsing the return of a unix command which has a header line that I don't need, and then 2 lines of information per item. Currently, I am doing this:

(undef, @ret) = map { [split /\n/] } split(/(?:Host: )/, `cat /proc/scsi/scsi`);

工作正常跳过头,给我每文本有用行一个数组元素。不过,我想建立一个哈希来代替,我就知道,除了额外的线怎么办。所以,我怎么能在code一行,忽略第一个数组元素,让我创造的哈希?我沿着片或接头的线的地方想,但我需要知道通过拆分主机上创建的数组的大小(这可能吗?)。我想我可以也做了(民主,民主基金,RET%)=地图{...}但如果这可以用一个切片或剪接来实现,这将是巨大的,以了解如何。

Which works fine to skip the header and give me one array element per "useful" line of text. However, I want to build a hash instead, which I would know how to do except for that extra line. So how can I, in a single line of code, ignore that first array element, to allow me to create the hash? I was thinking somewhere along the lines of a slice or a splice, but I would need to know the size of the array created by the split on Host (is that possible?). I guess I could also do a (undef,undef, %ret) = map {...} but if this could be done with a slice or a splice, that would be great to learn how.

推荐答案

从的 拆分 并仍然能够链上更多的命令是使用的 的grep 一个状态变量:

One way to remove the first element from a split and still be able to chain a more commands would be to use grep with a state variable:

use strict;
use warnings;

my @lines = do {
    my $line = 0;
    grep {++$line > 1} split /\n/, "1\n2\n3\n4\n5\n6\n7\n"
};

print "@lines";

输出:

2 3 4 5 6 7

不过,我认为你试图做太多code一行。

However, I think you're trying to do too much in a single line of code.

由于看来你只是读文件,我会建议你使用Perl 打开 的文件,而不是炮击了以

Since it appears you're just reading a file, I would suggest that you use Perl to open the file instead of shelling out to cat.

假设你的键/值分隔符是一个冒号,下面是我会建议你建立你的逻辑:

Assuming your key / value delimiter is a colon, the following is how I'd recommend you construct your logic:

use strict;
use warnings;
use autodie;

my %hash = do {
    open my $fh, '<', '/proc/scsi/scsi';
    <$fh>; # Skip Header Row
    map {chomp; split /:/, $_, 2} <$fh>
};

这篇关于perl的丢弃在地图操作第一个数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆