Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Include subs from different perl file

by TGI (Parson)
on Jun 06, 2007 at 19:39 UTC ( [id://619656]=note: print w/replies, xml ) Need Help??


in reply to Include subs from different perl file

Code reuse is a wonderful thing. You are getting great advice here. Use modules (see perlmod) and avoid globals, pass data to subs as arguments.

If you must use globals, you can either use package globals or import your variables so that you can see them in your main script. I'll show you how to specify the package of variables and subroutines here. Exporting/importing symbols is a bit more complex, so I'll leave that to the proper documentation.

File Foo.pm:

package Foo; my $hello; sub hello { print "$hello\n"; return; # I like explicit returns. }

File myscript.pl:

use strict; use warnings; use Foo; $Foo::hello = 'hello'; Foo::hello(); #prints "hello\n"

Also, ditch the unneeded & sigil from your subroutine calls. It can have unexpected consequences. Here are the relevent bits from perlsub, with emphasis added:

...If a subroutine is called using the & form, the argument list is optional, and if omitted, no @_ array is set up for the subroutine: the @_ array at the time of the call is visible to subroutine instead. This is an efficiency mechanism that new users may wish to avoid.
...
Not only does the & form make the argument list optional, it also disables any prototype checking on arguments you do provide. This is partly for historical reasons, and partly for having a convenient way to cheat if you know what you're doing. See Prototypes below.

See perlsub for more details.

I think I need to put together a meditation - Ampersand Considered Harmful...


TGI says moo

Replies are listed 'Best First'.
Re^2: Include subs from different perl file
by Anonymous Monk on Mar 13, 2013 at 18:27 UTC
    Well, on modern Perl incarnations, I have to do:
    our $hello;
    instead of
    my $hello;
    It will not print the string in that variable, if I use my. Otherwise, thanks. Yet another soul got a door opened to Perl Modules.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://619656]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-20 04:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found