从perl中的散列打印特定行

时间:2012-10-25 18:09:28

标签: perl

我的问题是如何从哈希中打印特定行。到目前为止的代码(谢谢Joel Berger):

#!/usr/bin/env perl

use strict;
use warnings;

use LWP::Simple;

my $content = get('http://temptrax.itworks.com/temp');
my %probes = $content =~ /Probe\s*(\d)\|\s*(\-?[\d\.]+)/gx;

foreach my $probe (sort keys %probes) {
  print "$probe => $probes{$probe}\n";
}

它的输出是:

1 => 74.0
2 => -99.9
3 => 74.4
4 => 68.1

如何获取要打印的特定行?如果我输入数字1,则只打印第1行。谢谢你看看这个。

更新:我终于能够在阅读之后弄明白了

#!/usr/bin/env perl
use v5.10.1;
use strict;
use warnings;

use LWP::Simple;

my $content = get('http://temptrax.itworks.com/temp');
my %probes = $content =~ /Probe\s*(\d)\|\s*(\-?[\d\.]+)/gx;

for ($ARGV[0]) {
  when(1) {print "$probes{1}\n"; }
  when(2) {print "$probes{2}\n"; }
  when(3) {print "$probes{3}\n"; }
  when(4) {print "$probes{4}\n"; }
  default {print "error"; }
}

UPDATE2:找出一种更简单的方法

#!/usr/bin/env perl
use v5.10.1;
use warnings;

use LWP::Simple;

my $content = get('http://temptrax.itworks.com/temp');
my %probes = $content =~ /Probe\s*(\d)\|\s*(\-?[\d\.]+)/gx;

$MyVar = $ARGV[0];
print $probes{$MyVar};

1 个答案:

答案 0 :(得分:3)

print $probes{1};

也许?相当简单。或者:

print "$_ => ", $probes{$_} for 1,2,4;  # selected numbers