Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open a file whose full name is unknown with Perl?

I want to know if there is anything that lets me do the following:

folder1 has files "readfile1" "f2" "fi5"

The only thing I know is that I need to read the file which starts with readfile, and I don't know what's there in the name after the string readfile. Also, I know that no other file in the directory starts with readfile.

How do I open this file with the open command?

Thank you.

like image 405
jerrygo Avatar asked Dec 12 '22 20:12

jerrygo


2 Answers

glob can be used to find a file matching a certain string:

my ($file) = glob 'readfile*';
open my $fh, '<', $file or die "can not open $file: $!";
like image 98
toolic Avatar answered Dec 15 '22 09:12

toolic


You can use glob for simple cases, as toolic suggests.

my ($file) = glob 'readfile*';

If the criteria for finding the correct file are more complex, just read the entire directory and use the full power of Perl to winnow the list down to what you need:

use strict;
use warnings;
use File::Slurp qw(read_dir);

my $dir   = shift @ARGV;
my @files = read_dir($dir);

# Filter the list as needed.
@files = map { ... } @files;
like image 21
FMc Avatar answered Dec 15 '22 11:12

FMc