简体   繁体   中英

How do I get the name of the currently-running Perl script?

I have a script

#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';
use feature 'say';
use autodie ':default';
use mwe 'tmp';

tmp();

that calls a Perl module mwe

use feature 'say';
package mwe;
use Cwd 'getcwd';
use Exporter qw(import);
our @EXPORT = qw(tmp);

sub tmp {
    say 'written by ' . getcwd() . '/' . __FILE__;
}
1;

but when I run this script, the filename appears from the module:

con@V:~/Scripts$ perl mwe.pl
written by /home/con/Scripts//home/con/perl5/perlbrew/perls/perl-5.34.0/lib/5.34.0/mwe.pm

I'm still new at writing modules, so criticism there is appreciated, if my minimal working example isn't well-written.

My question: I'm aware that I could pass the file /home/con/Scripts/mwe.pl as a parameter to the subroutine tmp , but is there a way that I could get a subroutine like tmp to return the script filename instead automatically?

Use

use FindBin qw( $RealScript );
say $RealScript;

or

use Cwd qw( abs_path );
say abs_path($0);

Most of the time, people actually want the directory in which the script resides. For that, use

use FindBin qw( $RealBin );
say $RealBin;

or

use Cwd qw( abs_path );
use File::Basename qw( dirname );
say dirname(abs_path($0));

Instead of this in mwe.pm:

say 'written by ' . getcwd() . '/' . __FILE__;

Use:

say 'written by ' . getcwd() . '/' . $0;

Please investigate the following code snippet if it comply with your question.

A variable declared with our $__SCRIPT__ = abs_path($0) in main script which takes name of the script $0 and adds absolute path.

This variable can be accessed from any module as $main::__SCRIPT__ .

use strict;
use warnings;
use feature 'say';

use Cwd 'abs_path';
use Test::Some;

our $__SCRIPT__ = abs_path($0);

my $args = {
              id  => '2000',
              str => 'Magic string'
           };

my $m = new Some($args);

$m->show();

Source code of module Test::Some

package Some;

use strict;
use warnings;
use feature 'say';

sub new {
    my ($class, $arg) = @_;
    my $self = bless {
            id      => $arg->{id},
            str     => $arg->{str}
    }, $class;

    return $self;
}

sub show {
    my $self = shift;

    say 'PACKAGE:  ' . __PACKAGE__;
    say 'PKG_FILE: ' . __FILE__;
    say 'SCRIPT:   ' . $main::__SCRIPT__;
    say 'SELF_ID:  ' . $self->{id};
    say 'SELF_STR: ' . $self->{str};
}

1;

Sample of output

PACKAGE:  Some
PKG_FILE: /kunden/homepages/6/d807xxxxxx/htdocs/.perl/Test/Some.pm
SCRIPT:   /homepages/6/d807xxxxxx/htdocs/work/perl/examples/xmodule.pl
SELF_ID:  2000
SELF_STR: Magic string

Reference: abs_path , Perl global variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM