[H-GEN] couple of small perl questions
Jason Parker-Burlingham
jasonp at uq.net.au
Fri Jan 17 02:45:56 EST 2003
[ Humbug *General* list - semi-serious discussions about Humbug and ]
[ Unix-related topics. Posts from non-subscribed addresses will vanish. ]
Tony Nugent <tony at linuxworks.com.au> writes:
> I have a text file that I'm reading in, it is created by a windows
> program so it has CR-LF terminated lines.
Byron has already addressed this; I'm also surprised there isn't an
easy answer in the Perl FAQ (perldoc -q <string> is your friend).
> Also, I'd like to get the called name of the actual script from
> within the program... unlike shell scripts (using $0 to refer to its
> called name), ARGV[0] refers to the first command line arguement.
$0 is what you want. See perlvar for more information. (Again, Byron
answered this perfectly well.)
> The script I'm writing will be "multi-functional" in that it will be
> hard-linked with several different names, and I want it to act
> differently depending on its called name.
Note that this isn't always recommended for GNU programs any more (I
forget why, but it should turn up if you google for it).
> And can the same thing be done with modules, is it possible for an
> external module (or even a perl function) to identify its own called
> name?
Okay. At *compile time* you can find the current module name by using
the special "__PACKAGE__" keyword:
$ perl
package Jason::Example;
print __PACKAGE__ . "\n"
Jason::Example
As for function names, and package names at run-time, hmm. The
perldoc for C<caller> says you can use it with an expression argument
to specify how many stack frames to backtrack, and index
appropriately, like this:
#!/usr/bin/perl -w
use strict;
sub subcaller {
my $subname = (caller(1))[3];
}
sub example {
return subcaller;
}
sub exampletwo {
return subcaller;
}
print example . "\n";
print exampletwo . "\n";
print subcaller . "\n";
__DATA__
main::example
main::exampletwo
Use of uninitialized value in concatenation (.) or string at foo.pl line 21.
The key is the expression "my $subname = (caller(1))[3];" which means
assign subname the fourth return value from caller(1), which means
"give me the calling function's details from one call up the stack
frame".
Whew!
Hope this helps.
jason
--
``I may have agreed to something involving a goat.'' -- CJ
--
* This is list (humbug) general handled by majordomo at lists.humbug.org.au .
* Postings to this list are only accepted from subscribed addresses of
* lists 'general' or 'general-post'. See http://www.humbug.org.au/
More information about the General
mailing list