您的示例数据存在一些问题,但我想我了解您要做什么。假设您想要第三个服务器值(而不仅仅是第 3 行),您可能希望拥有看起来像这样的代码......
#!perl
#some includes
use strict;
use warnings;
use Data::Dumper;
#set some vars
my $TargetFileName="data_file.txt";
my $TargetServerNumber=3;
#call the sub
my @ServerArray=GetServerName($TargetFileName);
#did we get anything back?
if(@ServerArray) {
#yep, we got some content
print "Server number ".$TargetServerNumber."/".($#ServerArray+1)." is \"".$ServerArray[$TargetServerNumber-1]."\"\n"; #array numbers are 0-based
} else {
#nope, we read the file but didn't any matching content
print "No servers found in file \"".$TargetFileName."\".\n";
} #end if
print "\n";
print "Here's what was loaded into \@ServerArray...\n";
print Data::Dumper::Dumper(@ServerArray); #so you can see the full content of @ServerArray
print "All Done\n";
exit;
#----- subs go here -----
sub GetServerName {
my $DataFileName=shift; #pull in the first arg - this alters @_ for the rest of the sub, so take care when doing this
my @ReturnArray;
#do some QA
if(!$DataFileName) {die "You need to provide a file name to use this sub.\n"} #do we have a file name?
if(!stat($DataFileName)) {die "The requested file name of \"".$DataFileName."\" does not exist.\n";} #does the file exist?
open(INFILE, "<".$DataFileName) or die "Unable to open \"".$DataFileName."\" - ".$!;
#ok, read the file content
while(my $Line=<INFILE>) {
chop($Line);
$Line=~s/^\s+//g; #remove leading white spaces
$Line=~s/\s+$//g; #remove trailing white spaces
if(!$Line) {next;} #blank line, skip it
#check for the headers
if($Line=~m/^Servers/) {next;} #skip lines beginning with "Servers"
if($Line=~m/^\(local\)/) {next;} #skip lines beginning with "(local)"
#if we get here, we must want the line content, so add it to the array
push(@ReturnArray, $Line);
} #end while
close(INFILE);
#send the array data back, if any
return @ReturnArray
} #end GetServerName sub
__END__
stuff below here does not need to be commented
我承认这不是解决问题的最佳方法,但与大多数 Perl hack 一样,它确实有效。您会注意到代码有点矫枉过正,并且在将数据传递给某些操作之前会进行验证检查 - 养成使用您使用的任何语言执行此操作的习惯。这将帮助您在出现问题时返回更有意义的错误,并且还会捕捉数据相关问题。示例代码还进行了一些数据清理,因为前导和尾随可能会在以后给您带来问题。空白行(清洁后)也被删除。
顺便说一句,我用作示例的数据文件看起来像这样......
Servers ::
(local)
Tomas-Server1
Tomas-Server2
Tomas-Server3
Tomas-Server4
Tomas-Server5
Tomas-ServerLast