Error opening a file located in the same directory

I was just starting to learn Perl, and I had a problem opening a file that is in the same directory as my program.

#!/usr/bin/perl -w $proteinfilename = 'NM_021964fragment.pep'; open(PROTEINFILE, $proteinfilename) or die "Can't write to file '$proteinfilename' [$!]\n"; $protein = <PROTEINFILE>; close(PROTEINFILE); print "Essa é a sequência da proteína:\n"; print $protein, "\n"; exit; 

When I specify the file directory, changing it from 'NM_021964fragment.pep' to '/Users/me/Desktop/programa/NM_021964fragment.pep', the program works. But doesn’t it work even without me, specifying the directory, since the program and the file are in the same folder?

+4
source share
2 answers

If you are reading a simple file, you can use the diamond <> operator for simplicity.

 use strict; use warnings; my $protein = <>; print "Essa é a sequência da proteína:\n"; print "$protein\n"; 

And use the script like this:

 perl script.pl NM_021964fragment.pep 

This will force you to use the correct paths, assuming you use tab autocomplete when running the script.

Using the command line argument in this way is somewhat unsafe, as you can execute arbitrary code through insecure open commands. You can use the ARGV::readonly module to prevent such things. Or just use the code itself, it's pretty simple:

 for (@ARGV){ s/^(\s+)/.\/$1/; # leading whitespace preserved s/^/< /; # force open for input $_.=qq/\0/; # trailing whitespace preserved & pipes forbidden }; 
+2
source

Relative paths refer to the current working directory, not the script directory. When the script worked, they turned out to be the same. But, as you have discovered, this is not always the case. You can use the following to achieve the behavior you described:

 use Cwd qw( realpath ); use Path::Class qw( file ); my $script_dir = file(realpath($0))->dir; my $input_file = $script_dir->file('NM_021964fragment.pep'); 
+1
source

All Articles