how Sub::Name set anonymous subroutine 's caller to NOT __ANON__? - perl

I reading programming perl, at chapter 12, the objects, has following documents :
The next::method has a similar problems because it uses the package of
its caller to figure out what class to look at. If you define a method
in Donkey from another package, next::method will break:
package main;
*Donkey::sound = sub { (shift)–>next::method(#_) };
The anonymous subroutine shows up in the stack with as _ ANON _, so next::method doesn’t know which package it is in. You can use the Sub::Name CPAN module to make it work out, though:
use Sub::Name qw(subname);
*Donkey::sound = subname 'Donkey::sound' => sub { (shift)–>next::method(#_) };
I am very inquisitive how Sub::Name module complete this work ? let the anonymous subroutine's caller not be __ANON__
very thanks your help :)

From inside an anonymous subroutine you can achieve this by setting *__ANON__ to the desired name:
$sub = sub {
local *__ANON__ = 'Donkey::sound';
...
but Sub::Name sets it from the outside. A quick glance at the code leads me to think that it's poking and prodding the same stuff that setting *__ANON__ does, and you can't do that from perl code. It's in XS because it has to be, not because it's faster that way.

Related

Why can we access the subroutine even after specifying it in EXPORT_FAIL?

Why, even after specifying subtract function in EXPORT_FAIL, am I able to access the function by defining it fully like mathematics::subtract? How can we completely make the function private?
package mathematics;
use Exporter;
#ISA = qw(Exporter);
#EXPORT = qw(add);
#EXPORT_FAIL = qw(subtract);
sub add() {
print("you can add numbers here"."\n");
}
sub subtract() {
print("you can subtract the numbers here"."\n");
}
1;
How can we completely make the function private???
You cannot. Perl doesn't have the concept of private or public.
You can however make it a lexical code reference and use that inside your code.
package Foo;
use strict;
use warnings;
my $_private = sub {
return "this is a secret";
}; # note the semicolon
sub bar {
return $_private->(); # call with reference syntax ->()
}
1;
As a lexical variable, it is now only accessible from within its scope. In this case, that scope is the file, not the package. So if you have multiple packages in one file, they can all see it. You cannot access it via a fully qualified name from outside the package.
By convention, things that should be handled as if they were private in Perl are named with a leading underscore _. That's how other developers know that something is not part of the public API of a module and that it's subject to change and should not be messed with. Of course that doesn't stop anybody from doing it, but generally there is no reason to stop them.
Also note that package names in Perl typically are written in camel case with the first letter being capitalised. Your package should be called Mathematics, and it should have use strict and use warnings.
From Perl 5.18, you can use lexical subroutines to achieve what you want. The documentation says this:
These subroutines are only visible within the block in which they are
declared, and only after that declaration:
# Include these two lines if your code is intended to run under Perl
# versions earlier than 5.26.
no warnings "experimental::lexical_subs";
use feature 'lexical_subs';
foo(); # calls the package/global subroutine
state sub foo {
foo(); # also calls the package subroutine
}
foo(); # calls "state" sub
my $ref = \&foo; # take a reference to "state" sub
my sub bar {
...
}
bar(); # calls "my" sub
p.s. Lexical subroutines are non-experimental from 5.26.

Query in Perl Subroutines

I've to use perl as a part of our internship, I've come across this piece of code and could not understand what this may mean.
$val->ReadSim($first_sim, \&DataProcessing);
In the script, subroutine DataProcessing is defined, but could not find ReadSim. I tried searching in our infrastructure but was not able to. This was given to me to understand a week ago and I can't ask the guide without losing credits...
Please help...
What you're seeing is not a mere subroutine, but a method on some object called $val.
I take it you might see something on top of the program like this:
use Foo::Bar; # Some Perl module
This Perl module will contain the method ReadSim. Somewhere in your code, you probably see something like this:
my $val = Foo::Bar->new; # If the people who wrote this followed standards...
This defines $val as an object of Foo::Bar. If you look in package Foo::Bar, you'd see something like this:
#! Foo/Bar.pm
package Foo::Bar;
use strict; # Because I'm an optimist
use warnings;
...
sub new {
my $class = shift;
...
my $self = {};
...
bless $self, $class;
...
return $self; # May simply be bless {}, $class;
}
Then further down, you'll see:
sub ReadSim {
my $self = shift;
...
}
The $self = {} is a reference to a Perl hash. This is how most objects are defined. That's pretty much all the constructor does. It defines a reference to something, then blesses it as that object type. Then, the methods are merely subroutines that take the defined object and manipulate that.
$val-> ReadSim(...);
is equivalent to:
Foo::Bar::ReadSim( $val, ... );
So much for your introduction to Object Oriented Perl by Fire. You still have a question about what does ReadSim mean.
If all is right in the world, the developer of that module should have created built in Perl documentation called POD. First, determine the type of object $val is. Look where $val is defined (Something like my $val = Foo::Bar->new(...);). The Foo::Bar is the class that $val is a member of. You can do this from the command line:
$ perldoc Foo::Bar
And, if you're lucky, you'll see the documentation for Foo::Bar printed out. If you're really, really lucky, you will also see the what ReadSim also does.
And, if you're not so lucky, you'll have to do some digging. You can do this:
$ perldoc -l Foo::Bar
/usr/perl/lib/perl5/5.12/Foo/Bar.pm
This will print out the location of where the Perl Module resides on your system. For example, in this case, the module's code is in /usr/perl/lib/perl5/5.12/Foo/Bar.pm. Now, you can use an editor on this file to read it, and search for sub ReadSim and find out what that subroutine ... I mean method does.
One final thing. If you're new to Perl, you may want to look at a few tutorials that come with Perl. One is the Perl Reference Tutorial. This tutorial will tell you about references. In standard Perl, there are three different types of variables: scalar, hashes, and arrays. To create more complex data structures, you can create hashes of hashes or hashes of arrays, or arrays of arrays, etc. This tutorial will teach you about how to do this.
Once you understand references, you should read the tutorial on Perl Object Oriented Programming. Object Oriented Perl uses references to create a simulated world object oriented programming design. (I say simulated because some people will argue that Object Oriented Perl isn't really object oriented since you don't have things like private methods and variables. To me, if you can think in terms of objects and methods as you program, it's object oriented).

Intercept nonexistent methods call in Perl

I try to intercept nonexistent methods call in some subclass.
Yes, I know about AUTOLOAD,
but (for methods) it try to call parent::method first, then UNIVERSAL::method and only then ::AUTOLOAD.
But I need call (something like) ::AUTOLOAD at first.
Because I want to know what methods subclass try to call from parent.
Give me some advice about it please.
If you just want to know what methods are being used, you can use some profiling module like Devel::NYTProf.
If you want to react to that during your program execution, you can intercept directly the entersub opcode just as the profiling modules do. See the perlguts or profiling module code for more details.
You could probably create a 'Monitor' class with FETCH and EXISTS and tie it to the symbol table hash like: tie %Module::Name:: , Monitor;
But unless we know exactly what you are trying to do and why, it's hard to guess what would be the right solution for you.
Please heavily consider Jiri Klouda's suggestion that you step back and reconsider what you are trying to accomplish. You almost never want to do what you're trying to do.
But, if you're really sure you want to, here's how to get enough pure Perl rope to hang yourself...
The subs pragma takes a list of sub names to predeclare. As tchrist says above, you can predeclare subs but never actually define them. This will short-circuit method dispatch to superclasses and call your AUTOLOAD immediately.
As for the list of sub names to pass to the pragma, you could use Class::Inspector->methods (thanks to Nic Gibson's answer for teaching me about this module).
According to brian d foy's comment to Nic Gibson's answer, Class::Inspector will not handle methods defined in UNIVERSAL. If you need to do those separately, you can get inspiration from the 'use subs' line in my Class::LazyObject module.
Why not create an AUTOLOAD sub in the sub-class package which 1) reports the missing method and then 2) dispatches the call to the parent. For this to work you don't defined #ISA in the sub-class.
Something like:
package my_parent;
sub foo { warn "in my_parent::foo" }
package my_subclass;
my $PARENT_CLASS = "my_parent"; # assume only one parent
# Note: no #ISA defined here
sub AUTOLOAD {
warn "non-existent method $AUTOLOAD called\n";
my $self = shift;
(my $method = $AUTOLOAD) =~ s{.*::}{};
my $super = $PARENT_CLASS . '::' . $method;
$self->$super(#_);
}
package main;
my $x = bless {}, 'my_subclass';
$x->foo;
The syntax: $self->$super(#_) where $super has double-colons in it tells perl in which package to start looking for the method, e.g.:
$self->my_parent::foo(...)
will look for the foo method starting in the package my_parent regarless of what class $self is blessed into.

To bless or not to bless, that is my question!

first post from a newbie-user. Every question I google seems to bring me here and I always get a great answer to what I'm looking for; so naturally this was my first stop when I began pondering the usage of blessing in Perl.
I've just gotten into Perl's OOP and just today read the post asking what bless does. I now understand that it references a scalar/hash/array to an object, 'attaching' it, if you will.
In most of the examples of classes I see in Perl, they don't seem to have properties like I'm used to seeing in other languages...
{ package Person;
my $property = "This is what I'm talking about :)";
sub new { ... }
...
}
So, I created a stupid class with a property to see what would happen. I gave the property the value 'NIL' right off the bat and then 'Not Nil!' in the constructor. Using a method LIST, I was able to print the property, and as I expected, it printed 'Not Nil!'
My question is, if properties work the same as I expected them to work (declared in the body) then why use bless at all? What is the added benefit of having that reference when you could simply create a scalar/hash/array as a property, or create whatever references you want as a property?
I hope I explained what I'm trying to ask well enough, very green with Perl :)
Well, that is not how you create classes in Perl.
Your $property variable is defined in package scope. Therefore, there will only one copy of it per class rather than each object having its own copy.
One might implement such a class using hash based objects the long and hard way as below:
#!/usr/bin/perl
package Person;
use strict; use warnings;
sub new {
my $class = shift;
my $self = {};
bless $self => $class;
my ($arg) = #_;
for my $property ( qw( message ) ) {
if ( exists $arg->{$property} ) {
$self->$property($arg->{$property});
}
}
return $self;
}
sub message {
my $self = shift;
return $self->{message} unless #_;
my ($msg) = #_;
$self->{message} = $msg;
}
package main;
my $person = Person->new({
message => "This is what I'm talking about :)"
});
print $person->message, "\n";
Now, this gets tedious fast. So, there are modules that help you deal with this as well as helping you define your classes in way that is safe for inheritance.
Class::Accessor is one such utility module.
For programs where startup time is not an issue, you should consider Moose. With Moose, you can write the above as:
#!/usr/bin/perl
package Person;
use Moose;
has 'message' => (is => 'rw', isa => 'Str');
__PACKAGE__->meta->make_immutable;
no Moose;
package main;
my $person = Person->new({
message => "This is what I'm talking about :)"
});
print $person->message, "\n";
You should read perldoc perltoot and Moose::Manual::Unsweetened for the standard way of doing things.
What you did with $property in this case is declared a variable in the "Person" package's scope. You change that inside (or outside using $Person::property) of the package, and any object that refers to it will see the updated variable, so it acts a lot like a "static attribute (Java)" without any real "private" scope. By convention, hidden things in Perl ("private" or "protected") are prefixed with an underscore, but of course this isn't enforced.
You don't actually make a new class, as you pointed out, with the "package" keyword; you can use "package" without OOP at all. That simply creates a separate "namespace".
The advantage of "blessing" a variable, almost always a hash reference from what I've seen, is that you can have methods, just like any other OOP language. Just remember to bless whatever you return in the new {} subroutine ("new" isn't actually a reserved word; just a convention). When you call a method on the "object" (a blessed data structure like a hashref), the first argument of the method is the data structure itself. So, if you have a hashref called $myobject, which is blessed to AwesomeClass, and you define a method in AwesomeClass called doSomethingAwesome, which needs to accept one variable, you would have to "shift" #_ (which is the argument list of the subroutine, or use $_[0]) to access the $myobject hashref. Python does something similar, and all languages pass the object reference to the method somehow. ("this" keyword in many, see also "thiscall" calling convention)
NB: I've seen lots Perl bashing in my time, which has only been a few years as a programmer. Perl is an awesome language that was made by a very smart linguist (Larry Wall) and has a fanatical following -- more fanatical at one time than Ruby, perhaps, but not as much as David Koresh). Perl does things very differently than lots of languages but if you look at code golf entries on this site and others, you can clearly see that much can be accomplished with very little Perl (no guarantees about code legibility, especially for newcomers!)
The value of bless'ing an object is getting to use the methods from a particular package.
package MyClass;
sub answer { my ($self)=#_; return $self->{foo} * 42; }
package main;
my $object1 = { foo => 1, bar => "\t" };
my $object2 = bless { foo => 2, bar => "\t" }, "MyClass";
$ref1 = ref $object1; # 'HASH'
$ref2 = ref $object2; # 'MyClass'
$answer1 = $object1->answer; # run time error
$answer2 = $object2->answer; # calls MyClass::answer, returns 2 * 42 = 84
Ugh... Sinan's answer is entirely too learned for my taste, at least past 12am :)
So I'll give a shorter and somewhat less Perly one, just for variety's sake.
Your question is not really about Perl as far as I can tell, and can be just as easily ased in another form: "Why bother using C++ and OOP in it when C already has structs?"
In other words, you seem to be asking what the point of using OOP paradigm is.
The answer is of course that it helps solving certain software engineering problems easier than pure procedural programming. Emphasis on certain - OOP is not a panacea for every problem, any more than ANY technique/approach/paradigm is.
Using OOP (in a form of packages as classes and blessed hashes as objects in Perl) allows you to enjoy the benefits of inheritance, polymorphism and other OOPyish mumbo-jumbo which you are probably already fairly familiar with from you non-Perl OOP experience.
Can you do 100% of what you'd have done with a blessed object with a pure data structure? Absolutely. Would 100% of it be just as easy/short/readable/maintainable code as you can achieve using objects? Most likely not, though it depends on how well your OOP code actually leverages the benefits that OOP provides (BTW, I have encountered supposedly OOP code (Perl and not) which wasn't really taking any advantage of OOP paradigm and could have been made easier to read and understand had it been stripped of its OOP chrome).

Can Perl method calls be intercepted?

Can you intercept a method call in Perl, do something with the arguments, and then execute it?
Yes, you can intercept Perl subroutine calls. I have an entire chapter about that sort of thing in Mastering Perl. Check out the Hook::LexWrap module, which lets you do it without going through all of the details. Perl's methods are just subroutines.
You can also create a subclass and override the method you want to catch. That's a slightly better way to do it because that's the way object-oriented programming wants you do to it. However, sometimes people write code that doesn't allow you to do this properly. There's more about that in Mastering Perl too.
To describe briefly, Perl has the aptitude to modify symbol table. You call a subroutine (method) via symbol table of the package, to which the method belongs. If you modify the symbol table (and this is not considered very dirty), you can substitute most method calls with calling the other methods you specify. This demonstrates the approach:
# The subroutine we'll interrupt calls to
sub call_me
{
print shift,"\n";
}
# Intercepting factory
sub aspectate
{
my $callee = shift;
my $value = shift;
return sub { $callee->($value + shift); };
}
my $aspectated_call_me = aspectate \&call_me, 100;
# Rewrite symbol table of main package (lasts to the end of the block).
# Replace "main" with the name of the package (class) you're intercepting
local *main::call_me = $aspectated_call_me;
# Voila! Prints 105!
call_me(5);
This also shows that, once someone takes reference of the subroutine and calls it via the reference, you can no longer influence such calls.
I am pretty sure there are frameworks to do aspectation in perl, but this, I hope, demonstrates the approach.
This looks like a job for Moose! Moose is an object system for Perl that can do that and lots more. The docs will do a much better job at explaining than I can, but what you'll likely want is a Method Modifier, specifically before.
You can, and Pavel describes a good way to do it, but you should probably elaborate as to why you are wanting to do this in the first place.
If you're looking for advanced ways of intercepting calls to arbitrary subroutines, then fiddling with symbol tables will work for you, but if you want to be adding functionality to functions perhaps exported to the namespace you are currently working in, then you might need to know of ways to call functions that exist in other namespaces.
Data::Dumper, for example, normally exports the function 'Dumper' to the calling namespace, but you can override or disable that and provide your own Dumper function which then calls the original by way of the fully qualified name.
e.g.
use Data::Dumper;
sub Dumper {
warn 'Dumping variables';
print Data::Dumper::Dumper(#_);
}
my $foo = {
bar => 'barval',
};
Dumper($foo);
Again, this is an alternate solution that may be more appropriate depending on the original problem. A lot of fun can be had when playing with the symbol table, but it may be overkill and could lead to hard to maintain code if you don't need it.
Yes.
You need three things:
The arguments to a call are in #_ which is just another dynamically scoped variable.
Then, goto supports a reference-sub argument which preserves the current #_ but makes another (tail) function call.
Finally local can be used to create lexically scoped global variables, and the symbol tables are buried in %::.
So you've got:
sub foo {
my($x,$y)=(#_);
print "$x / $y = " . ((0.0+$x)/$y)."\n";
}
sub doit {
foo(3,4);
}
doit();
which of course prints out:
3 / 4 = 0.75
We can replace foo using local and go:
my $oldfoo = \&foo;
local *foo = sub { (#_)=($_[1], $_[0]); goto $oldfoo; };
doit();
And now we get:
4 / 3 = 1.33333333333333
If you wanted to modify *foo without using its name, and you didn't want to use eval, then you could modify it by manipulating %::, for example:
$::{"foo"} = sub { (#_)=($_[0], 1); goto $oldfoo; };
doit();
And now we get:
3 / 1 = 3