How to open a file whose full name is unknown to Perl?

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

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

The only thing I know is that I need to read the file that starts with readfile, and I don’t know what is in the name after the line readfile. In addition, I know that no other file in the directory starts with readfile.

How to open this file using the command open?

Thank.

+3
source share
3 answers

glob can be used to search for a file matching a specific line:

my ($file) = glob 'readfile*';
open my $fh, '<', $file or die "can not open $file: $!";
+10
source

glob , .

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

, Perl, , :

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;
+2

You do not need to import to read the contents of the directory. Perl has built-in functions that can do this:

opendir DIR, ".";
my ($file) = grep /readfile.*/, readdir(DIR);

open FILE, $file or die $!;
+1
source

Source: https://habr.com/ru/post/1754896/


All Articles