Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

How do I include a file and execute the code in the file?

by xorl (Deacon)
on May 16, 2001 at 20:12 UTC ( [id://80940]=perlquestion: print w/replies, xml ) Need Help??

xorl has asked for the wisdom of the Perl Monks concerning the following question: (files)

This is basically my script ....
if ($var eq "foo") { Include file1.pl and execute code } if ($var eq "bar") { Include file2.pl and execute code } else { Include file1.pl and execute code }
I tried using require but if I need to include the same file twice it tells me the libary is already loaded. Idealy I'd like something like PHP's include command.Any suggestions?
Thanks!
Xorl

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I include a file and excude the code in the file?
by Albannach (Monsignor) on May 16, 2001 at 21:00 UTC
    Have you looked at do?
Re: How do I include a file and execute the code in the file?
by tachyon (Chancellor) on May 21, 2001 at 09:18 UTC
    Use this sub:
    # Useage example: my $error = run_code('/file1.pl'); print "Run code failed, err msg:\n$error" if $error; sub run_code { my $path = shift; open(CODE, $path) || return "Oops: $path $!\n"; local $/; my $code = <CODE>; eval $code; return $@; }
    Needs full path to code to be run.

    The local $/ gives a locally undefined value to the input record seperator $/ with the result that we glob the whole file into $code. This saves us from @code = <CODE>; $code= join'',@code;

    The sub returns undef if it suceeds or the error message if it fails to run the code.

    Hope this helps.

    tachyon

Re: How do I include a file and execute the code in the file?
by chromatic (Archbishop) on May 21, 2001 at 05:57 UTC
    Write a module that exports functions. Call the functions instead of requireing the file. See perlmod or use Super Search to look for 'writing a module'.
Re: How do I include a file and execute the code in the file?
by Anonymous Monk on Jun 04, 2001 at 10:04 UTC
    or why not simply use it like this? do 'something.pl'
Re: How do I include a file and execute the code in the file?
by ton (Friar) on May 20, 2001 at 00:38 UTC
    Umm... why would you need to include the file twice? If you don't like require complaining, you can store the files you've already included in a hash, then include files only if they are not already in the hash...

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2024-03-28 11:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found