我有一个.conf文件,其中要执行的测试列表以一行形式编写,每个测试具有不同的场景。 看起来像这样:
scenario1,scenario2
scenario1,scenario2,scenario3
scenario1
在我的代码中,我打开文件:
sub get_tests {
my $nb_tests = 0;
my @length_tests;
my @lists_scenarios;
my @current_list;
my $current_length;
# Open the conf file with all the tests to execute
my $filename = $folder_lists_scenarios.$scenario_list.".conf";
open(my $fh, '<:encoding(UTF-8)', $filename) or die $!;
# open my $fh, "<", $folder_lists_scenarios.$scenario_list.".conf" or die $!;
# Get all the scenarios
while (my $row = <$fh>) {
chomp $row; # delete carrier return
$nb_tests++; # increment number of tests
@current_list = split(/,/, $row); # separate the test into scenarios
$current_length = @current_list; # get the number of scenarios in the test
push @length_tests, $current_length; # store the number of scenarios
push @lists_scenarios, [@current_list]; # store the list of scenarios of the test
}
# Close the file
close $fh;
return ($nb_tests, \@length_tests, \@lists_scenarios);
}
我的问题是我使用这些字符串打开了具有字符串名称的文件:
sub open_txt {
# Open a txt file and return then content in an array
my $filename = "folder_with_scenarios/".$_[0]."/content.txt";
my @lines;
my $temp;
open(my $fh, '<:encoding(UTF-8)', $filename) or die "Could not open file '$filename'. Please check if the file name is correct or in the good repertory.";
my $cnt_line = 0;
while (my $row = <$fh>) {
chomp $row;
$cnt_line++;
if ( length($row) > 1 ) { # if the line is not empty
$temp = length($row);
push @lines, $row
}
}
# If the file is not empty
if ($cnt_line > 0) {
return ($cnt_line, @lines);
# If the file is empty
} else {
die "[ERROR] The file $filename is empty\n";
}
}
当我这样做时,该行的第一种情况运行良好,但最后一行却出错:
Uncaught exception from user code:
/content.txt'. Please check if the file name is correct or in the good repertory. at ./my_code.pl line 2219.
main::open_txt('folder_with_scenarios/scenario2\x{d}/content') called at ./my_code.pl line 2588
很明显,我在行字符串的末尾有一个\ x {d},但我不知道如何摆脱它。
有什么想法吗?
谢谢
SLP
答案 0 :(得分:3)
您要传递给open_txt
的值以回车符结束。
您大概是从非Windows计算机上具有Windows(CRLF)行尾的文件中读取值的。
您大概是使用chomp
来删除换行符,但仍将回车符保留在适当的位置。
如果是这样,请替换
chomp;
与
s/\s+\z//;