I’m trying to develop a perl script that looks through all of the user’s directories for a particular file name without the user having to specify the entire pathname to the file.
For example, let’s say the file of interest was focus.qseq. It’s located in /home/path/directory/. At the command line, normally the user would have to specify the pathname to the file like in order to access it, like so: /home/path/directory/focus.qseq.
Instead I want the user just to have to enter sample.qseq in the command line, then the perl script will automatically assign the correct file to a variable. If the file is a duplicate but in separate directories, then the terminal will display the full pathname to those files and the user can better specify the file they meant.
I read about the File::Find module but it doesn’t do quite what I want.
Here’s my best attempt at implementing the code as I described above:
#!/usr/bin/perl
use strict; use warnings;
use File::Find;
my $file = shift;
# I want to search from the top down (you know, recursively) so first I look in the home directory
# I believe $ENV{HOME} is the same as $~/home/user
find(\&wanted, @$ENV{HOME});
open (FILEIN, $file) or die "couldn't open $file for read: $!\n";
I don’t really understand how the wanted subroutine works in this module. If anyone knows another way to implement the code I describe above, please feel free to make a suggestion. thank you
EDIT:
What if I wanted to utilize the command line option. Like so:
#!/usr/bin/perl
use strict; use warnings;
use File::Find;
use Getopt::Long qw(GetOptions);
my $file = '';
GetOptions('filename|f=s' => \$file);
# I believe $ENV{HOME} is the same as $~/home/user
find(\&wanted, @$ENV{HOME});
open (FILEIN, $file) or die "couldn't open $file for read: $!\n";
how would the implementation be for this one?
One problem is that you try to open the file without specifying the path. You need to create another variable, say
$path. Now, you can pass\&wantedas a reference to a subroutine that you write elsewhere, but you might have to resort to global variables. Using a closure would be better.Your code might look like this then: