upstream
upstream

Reputation: 25

Reading several XML files into an array and parsing them with Perl

I would like to read multiple XML files in an array and then parse them one by one.

Here is what I am doing:

my $output = "c:\documents\outputfiles";
opendir (FILE, $output) or die "can't open the $output";

my @files = readdir File;
print @files; 

This will list all the files under "outputfiles" directory. How do I just read the XML files?

I also tried:

my @files = grep {*.xml} readdir FILE;

This does not work.

Upvotes: 1

Views: 533

Answers (3)

simbabque
simbabque

Reputation: 54333

You need to supply a pattern to grep like this:

my @files = grep {/\.xml$/i} readdir FILE;

Upvotes: 0

Jean
Jean

Reputation: 22705

Try this:

@files = glob("C:/documents/outputfiles/*.xml");

@files is list of all xml files.

EDIT: Inserted full path in glob function according to TLP's comment.

Upvotes: 2

Sebastian Stumpf
Sebastian Stumpf

Reputation: 2791

Grep takes either an expression or a block as its first parameter. Also consider using autodie:

use autodie;
my $path = './files';

opendir(DIR, $path);
my @files = grep { -f "$path/$_" && m/.xml$/ } readdir(DIR);
closedir(DIR);

say for @files;

Upvotes: 0

Related Questions