0

我想像下面这样运行它

$ perl test.pl tex
结果:
1. 德克萨斯州
2. 休斯敦,德克萨斯州
3. DFW 德克萨斯州

选项?2
远程登录:德克萨斯州休斯顿

我基本上是想搜索一个数组,并为其分配一个数值,然后每次调用它而不是完整的值。

4

2 回答 2

1

这是一件比看起来更简单的事情。

use strict;
use warnings;

@ARGV == 1 or die "Usage: perl test.pl <location>\n";

my $place = quotemeta shift;

open my $fh, '<', 'telnets.txt' or die $!;
my @telnets = grep /$place/i, <$fh>;
die "No matching telnets\n" unless @telnets;
chomp @telnets;

print "RESULTS:\n";
printf "%d . %s\n", $_ + 1, $telnets[$_] for 0 .. $#telnets;
print "\n";

print "Option? ";

my $option = <STDIN>;
$option =~ s/\s+//g;

die "Invalid selection $option\n" unless $option > 0 and $telnets[$option-1];

print "Telneting to: $telnets[$option-1]\n";
于 2012-06-22T20:17:54.977 回答
0

让文件places.txt包含

Texas
Houston Texas
DFW Texas

然后,以下 Perl 脚本会执行您想要的操作。脚本中的注释解释。

#!/usr/bin/perl

use warnings;
use strict;
use integer;

our $filename_place = 'places.txt';
our $index_field_width = 2;

# Read in the place data.
my @place;
open PLACE, '<', $filename_place;
while (<PLACE>) {
    chomp;
    push @place, $_;
}
close PLACE;

# Print a menu.
for (my $i = 0; $i < @place; ++$i) {
    printf "%${index_field_width}d. %s\n", $i+1, $place[$i];
}

# Let the user choose.
print "\nOption? ";
my $option = <>;
chomp $option;
$option >= 1 && $option <= @place
  or die "$0: the option chosen is out of range\n";

# Act on the user's choice.  (Of course, you can put
# here whatever action you like but, as written, the
# following produces your sample output.)
print "Telneting to: ${place[$option-1]}\n\n";
于 2012-06-22T18:00:48.643 回答