нежелательный \ x {d} при открытии файла - PullRequest
0 голосов
/ 25 апреля 2019

У меня есть файл .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

1 Ответ

3 голосов
/ 25 апреля 2019

Значение, которое вы передаете open_txt, заканчивается возвратом каретки.

Предположительно, вы читаете значение из файла с окончаниями строк Windows (CRLF) на компьютере, отличном от Windows.

Вы предположительно использовали chomp для удаления перевода строки, но оставили возврат каретки на месте.

Если это так, замените

chomp;

на

s/\s+\z//;
...