python feature in perl?

M

Mike

I like that in python you can say:

if __name__ == "__main__"
tests

To know if you are running a $module.py file stand alone or if the
$module.py file has been included into a different, super python
script. Is there a similar feature in PERL? I've been using PERL
for a long time and I don't remember anything like this. I can think
of a way to emulate the feature, but I prefer to have a built in
instead of an emulation hack.

Mike
 
F

fB

Eric Pozharski said:
die unless caller;

There can be dragons though.

Depending on intended use it might be better to use __PACKAGE__ (as documented
in perlmod) rather than caller. For one, I find it easier to understand its
purpose:

if ( __PACKAGE__ eq 'main' ) {
tests;
}

or even, in case 'tests' represents a single statement:

tests if __PACKAGE__ eq 'main';

Moreover, should you need the return value from caller, you must remember to
check that you are using the correct context:

#!/usr/bin/perl

use strict;
use warnings;
use feature ':5.10';
{
package test;

sub check {
say scalar caller if caller;
return;
}
}

say scalar caller if caller;

test::check;

exit;
 
E

Eric Pozharski

*SKIP*
Moreover, should you need the return value from caller, you must
remember to check that you are using the correct context:

Yup, I've got where dragons are. My fault.
#!/usr/bin/perl

use strict;
use warnings;
use feature ':5.10';
{
package test;

sub check {
say scalar caller if caller;
return;
}
}

say scalar caller if caller;

test::check;

exit;

(somewhat reworked) that shows that C<die unless caller> fails inside
subroutines (even if in package C<main>.

#!/usr/bin/perl

use strict;
use warnings;
use feature ':5.10';
sub check {
say '>', scalar caller if caller;
return;
}

say '<', scalar caller if caller;
check;

Then gives false positives outside C<main>

#!/usr/bin/perl

package Foo;
use strict;
use warnings;
use feature ':5.10';
sub check {
say '>', scalar caller if caller;
return;
}

say '<', scalar caller if caller;
check;

So C<die unless caller> detects only one thing -- that point is outside
of any subrotine. Quite useles. Shame on me.

darn, darn dragons.
all around me.
perldoc dies on you.
 
P

Peter J. Holzer

I like that in python you can say:

if __name__ == "__main__"
tests

This is a bad example. Perl already has a testing framework. If you want
to add tests to your module, put them into the t/ direcory, not inside
your module.

There might be better examples for when this feature is useful, but I
cannot think of any at the moment.

hp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,281
Latest member
Pedroaciny

Latest Threads

Top