La variable d'environnement PWD
contient le répertoire de travail en cours, qui doit correspondre au chemin d'exécution du script.
Vous pouvez déduire le chemin complet du script avec $ENV{PWD}
et $0
Modifier: fournir un exemple de code, car il est difficile pour certains à croire que cela est possible:
Je ne peux pas avoir pris tous les cas possibles, mais cela devrait être très proche:
use strict;
use warnings;
print "PWD: $ENV{PWD}\n";
print "\$0: $0\n";
my $bin = $0;
my $bin_path;
$bin =~ s#^\./##; # removing leading ./ (if any)
# executed from working directory
if ($bin !~ m#^/|\.\./#) {
$bin_path = "$ENV{PWD}/$bin";
}
# executed with full path name
elsif ($bin =~ m#^/#) {
$bin_path = $0;
}
# executed from relative path
else {
my @bin_path = split m#/#, $bin;
my @full_path = split m#/#, $ENV{PWD};
for (@bin_path) {
next if $_ eq ".";
($_ eq "..") ? pop @full_path : push @full_path, $_;
}
$bin_path = join("/", @full_path);
}
print "Script Path: $bin_path\n";
sortie de test est exécuté:
PWD: /tmp
$0: ../home/cmatheson/test.pl
Script Path: /home/cmatheson/test.pl
PWD: /home/cam
$0: ./test.pl
Script Path: /home/cam/test.pl
PWD: /usr/local
$0: /home/cam/test.pl
Script Path: /home/cam/test.pl
PWD: /home/cam/Desktop/foo
$0: ../../src/./git-1.7.3.2/../../test.pl
Script Path: /home/cam/test.pl
« Je préfère ne pas utiliser des modules spéciaux » -- Pourquoi? Notez qu'il y a beaucoup de modules qui sont fournis avec la distribution perl, aussi. – Ether
@ether - pour la même raison que je n'aime pas ketchup sur les hot-dogs je suppose – CheeseConQueso