Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

determine basename of script via program 2

Status
Not open for further replies.

Hemo

Programmer
Apr 9, 2003
190
US
I need to determine the name of the running script from within itself _without_ using a module.

I've settled on using this:
Code:
$SELF = `basename $0`;

Just checking to see if there is anything more 'elegant', anything within Perl itself that doesn't requite me running a system command sort of thing.
Again, I need to do this withot a module such as File::Basename.

 
This short script demonstrates one way, there are others I'm sure.

sub basename($){

my $var = shift;

# print "$var\n";

while ( $var =~ /\/|\\/ ){
$var = $';
}

# print "$var\n";

return $var;

}


print basename($0), "\n";


Mike

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

It's like this; even samurai have teddy bears, and even teddy bears get drunk.
 
I usually do something like this:
Code:
(my $routine = $0) =~ s{^.*(\\|/)}{};
This gets rid of everything through the rightmost path separator, leaving just the program name. (Assuming your path separator is "\" or "/", as on Windows or Unix.)

I think I got this from The Perl Cookbook originally.
 
nice and neat -- mine's easier to read though :p

Mike

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

It's like this; even samurai have teddy bears, and even teddy bears get drunk.
 
thanks guys. Appreciate the feedback.
 
From those answers, I'd go for mikevh's. I'd be uncomfortable using $'.

According to perlvar, "The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches."


 
I agree with ish on that one. If speed's what you're after, then you're better off not using a regex at all.
Code:
print substr($0, rindex($0, '/')+1);
You have to hard-code your directory separator, do some testing of return values, or check $^O and set the dir separator. Really, this is why you use modules so you never have to check. A unix filename can contain any character other than a /, so if you have some goofy filename with a \ in it, it'd get parsed out as a dir separator.

________________________________________
Andrew - Perl Monkey
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top