1

Consider:

File display.pl

disp{
    my $p = shift;
    print $p;
}

File temp.pl

require "display.pl";

$item = "asd";

&disp($item);

When I executed temp.pl, it gave an error:

can't find method "disp" without a package or a object reference at display.pl line 2.

1
  • 2
    You should use disp($item), not &disp($item), unless you specifically mean to circumvent prototypes. If you have no idea what that meant, just don't use &. See perlsub for the full explanation. Commented Mar 2, 2012 at 14:29

2 Answers 2

11

You forgot to write sub before disp{ in display.pl, so Perl doesn't know that you are trying to define a function.

Always use strict and warnings, and you will avoid such problems. Also, as noted by @NEW, you need to end display.pl with a 1; because require requires that a file end with a true value.

Corrected, your code would be:

use strict;
use warnings;

sub disp {
    my $p = shift;
    print $p;
}

1;
Sign up to request clarification or add additional context in comments.

Comments

5

Avoid errors by using

use strict ;
use warnings;

Note that you need the 1; at the end of the file like

sub disp{ 
    my $p=shift;  
   print $p;
 } 
1;

This is because Perl needs the last expression in the file to return a true value.

If the require file (display.pl) is in another directory you will need to specify the absolute path:

You don't need to worry about recursive requiring (e.g. requiring a file that requires the current file), Perl will handle everything.

SEE ALSO

perldoc -f require and perldoc -q require and perldoc perlmod for better understanding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.