How to include a file in perl

hi…

I written a file with basic operation …When i tried to include as i did in php it shows error… like include “a.pl”.

How to include a file in perl…

I’m not exactly sure how, but I’m sure you could find something on google:

http://www.google.com/search?hs=kRY&hl=en&lr=&safe=off&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial_s&q=perl+include+functions&btnG=Search
http://www.google.com/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial_s&hl=en&q=include+files+in+perl&btnG=Google+Search

You shouldn’t be including files in Perl as you do in PHP, it doesn’t work the same way.

Ideally you should be importing modules (.pm-files) into your file with the “use” statement. However, if you’re unable to change the way your setup works you can fudge it with the require-statement:
require “filename.pl”

No i cant do it can u plase give with an example…

I did:

require “filename.pl”

just to expand:

require “path/to/filename.pl”;

if the file is in the same folder as your main perl script you can just use it as KTotte has:

require “filename.pl”;

if you use “use” your file should be named with a .pm extension and placed in the same folder as the main perl script:

use Filename;

or you can use the “use lib” pragma to add modules to the @INC array and put them in any folder you want as long as you tell “lib” where you put your modules. No quotes around the filename and the convention is to capatalize at least the first character of a module name. Then in your module it’s always best to put:

1;

as the very last line because perl checks that the module will return some true value.

ya kevin i used like this but not working

hi i ammhaving two file inc.pl and inc1.pl

here is my simple code

/********************/

#!/usr/bin/perl -w

my $name = “arun”;

/********************/
#!/usr/bin/perl -w

require “inc.pl”;

my $var = $name;

print $var;

/*******************/

here when i tried to print it is showing error y???

/*******************/

Hello any body tell me an example i searched in google i cant find…

I just found this post and notice it’s not resolved yet - I need to do the exact same thing - my PERL skills are rusty - anyone figure out how to include a config file with some externally set variables?

yes, where there’s a will, there’s a way! :smiley:

it does not work because you declare $name private with the use of my.
You could remove the my and it would work, e.g. inc.pl could look like

$name = "arun";
1; # To make sure that we return TRUE statement

I would recommend though that you read on the differences of “require” (imported at runtime) and “use” (compile time) and on packages in general in Perl.
You can easily get into a mess and have insecure scripts otherwise.
That is the bad thing about Perl (and sometimes good as well :wink: ), that your code can look very messy and still halfway do the work it is suppose to do.

hey thanks for that - I totally forgot about the trailing “1;”