Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hai,

How to open a in perl ie., i want to open a XML file without name specified but with extension.

$file="abc.xml"; # Not by this method

open IN, "$file";

$file="(.*).xml"; # Something like this method

open IN, "$file";

Pardon me for this doubt, as for as i am new to perl.

With Regards,
RSP

Replies are listed 'Best First'.
Re: File open
by Corion (Patriarch) on Jul 17, 2007 at 13:47 UTC

    Traditionally, "the shell" does all the wildcard expansion, except on Windows. If you want to find files based on some wildcard expression, you can use the built-in glob function, the core module File::Find or File::Find::Rule if you want to write the search criteria in Perl.

    Using glob() is the easiest way if you just want to search one directory for files specified by extension:

    use strict; use File::Glob qw(bsd_glob); # switch on sane whitespace semantics for + glob my @files = glob('*.xml'); print "I found the following files:\n"; print "$_\n" for @files;

    If you want to use File::Find, because you want to search a whole directory tree, it's also easy:

    use strict; use File::Find; my @files; find(sub { push @files, $File::Find::name }, '.'); print "I found the following files:\n"; print "$_\n" for @files;
Re: File open
by leocharre (Priest) on Jul 17, 2007 at 17:39 UTC
    Here's another example:
    #!/usr/bin/perl -w use strict; use File::Slurp; my $abs_loc = '/path/to/my/xml/files'; opendir(DIR,$abs_loc) or die($!); my @xml_files = grep { /\.xml$/i and -f } readdir DIR; closedir DIR; for (@xml_files){ my $xml_content = File::Slurp::slurp("$abs_loc/$_"); # ... print STDERR "$xml_content\n"; }