in reply to Custom Module question

The warning about uninitialized value is because in line 6 of the code you posted you set $name to contain nothing, and then in line 8 of the code you posted, you call printname($name). As the printname function executes, it attempts to print "Hello $name\n", where $name is empty (or undef), and this throws a warning.

Later when you call printname("John"), it actually works, because the parameter you pass in is not empty; it contains "John".

There are other issues, such as calling printname from your package main without your printname.pm module actually exporting the subroutine. But apparently your actual usage is not exactly as described, because you didn't mention that error. If you are seeing that error but simply not mentioning it, you should look at Exporter for solutions.

Additionally, you really should be using lexical variables in your subroutine that are scoped to the subroutine itself, not to the entire file: my ($name) = @_; would be a good start.


Dave

Replies are listed 'Best First'.
Re^2: Custom Module question
by GrandFather (Saint) on Dec 03, 2014 at 22:56 UTC

    In fact the missing package name related error is shown by the OP:

    Undefined subroutine &main::printname called at testmodule.pl line 8.

    in the last line of the error output shown.

    As a general thing I prefer to use an explicit package instead of Exporter to avoid name clashes and make the province clear.

    Perl is the programming world's equivalent of English

      Oh you are so right. I was so focused on the crazy call with an undefined value I missed the 2nd message. Apologies.


      Dave