Perl 코드는 동일한 확장자를 가진 여러 파일(.xml)을 참조합니다.

Perl 코드는 동일한 확장자를 가진 여러 파일(.xml)을 참조합니다.

여러 XML 파일을 구문 분석하려고 하는데 약간의 문제가 있습니다. 아래 스크립트 섹션은 $twig->parsefile("output_1.xml"); 해당 파일을 잘 구문 분석합니다. 그러나 디렉터리의 모든 .xml 파일을 구문 분석하고 싶습니다. 나는 다음과 같은 코드로 각 파일을 작성해 보았습니다.

$twig->parsefile("output_1.xml" "output_2.xml" "output_3.xml");

또한 Bash에서와 같이 와일드카드를 사용해 보았습니다.

$twig->parsefile("*.xml");

그러나 이러한 시도 중 어느 것도 성공하지 못했습니다. 디렉터리의 모든 .xml 파일을 구문 분석하도록 스크립트를 어떻게 변경합니까? 지식이 부족해서 죄송합니다. 저는 이제 막 Perl을 사용하기 시작했습니다.

#!/bin/perl -w

use strict;
use XML::Twig;

my $twig = XML::Twig->new(
   twig_handlers => {item => \&acct}
);
$twig->parsefile("output_1.xml");                              

sub acct {
    my ($t, $elt) = @_;

          for my $tag (qw(itemId title viewItemURL convertedCurrentPrice)) {
                    print $elt->field($tag), "\n";
                        }
                            print "\n";
                            print "\n";
                            }

답변1

다음과 같이 디렉터리 내용을 열거할 수 있습니다.

my @files = <*.xml>;    # or: my @files = </your/path/to/*.xml>;
foreach my $file (@files) {
    $twig->parsefile($file);
}

관련 정보