1

Possible Duplicate:
What are valid Perl module return values?

Generally we use 1; at the end of the module. This is to indicate that module returns true and can be imported properly. Now if we return 0 means false, that means module fails in import.

My question is, What if I use (or return) below statements at the end of module

  • -1;
  • some text;
  • or abc;

Does -1 means error, and some text,abc means true

Also what if I don't use 1; or any statement (as above) at all, what does module return in that case?

Does it return undef?

Community
  • 1
  • 1

3 Answers3

4

Any true value indicates success. -1 is a true value.

The return doesn't have to be at the end of the file; it is the return value of the last executable statement (that is, the last statement that isn't just a compile-time thing like package, use, no, sub, format).

For example, the requiring a file containing the following:

package foo;
our @x;
sub bar { }

will fail if @foo::x is empty and otherwise succeed.

If there indeed are no executable statements, the return value is taken to be undef (false).

ysth
  • 96,171
  • 6
  • 121
  • 214
2

Just like for a sub, the value returned by a module is the value returned by the last statement evaluated. I imagine it's undef if the file is empty. (It's definitely not a true value.)

A module should always return a true value (anything other than zero, the empty string or undef).

  • -1 is true, so that's acceptable.
  • some text is an indirect method call equivalent for text->some().
    • text->some() (and equivalent) is acceptable if and only if the method returns a true value. I would follow up with a true constants to be safe.
  • abc is either a subroutine call equivalent to abc(), or a string literal equivalent to 'abc'.
    • abc() (and equivalent) is acceptable if and only if the subroutine returns a true value. I would follow up with a true constants to be safe.
    • 'abc' (and equivalent) is true, so that's acceptable.

If there's an error, die instead. But even that should be avoided if reasonable as it leaves the module half-loaded (half-executed) if someone catches the exception.

ikegami
  • 367,544
  • 15
  • 269
  • 518
1

Those are true and the module will compile. However, under more aggressive diagnostics I've seen compilers emit a warning about values other than 1. Actually this "1;" can be placed on any line. I sometimes put such in the middle of code I'm debugging just to have nice debugging break point lines.

A lot of programs out there run without trouble at lower diagnostic levels by accidentally having various true values in the last expression, which need not be the last line.

$a = "True value to accidentally keep -c happy.";

sub hello { return; }
Gilbert
  • 3,740
  • 17
  • 19