rich731 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I am trying to pass a variable as an argument to a module but it is returning a hash. Not sure what I'm missing.

Here is the module:

package htmlCode2; use CGI; use DBI; #Create new CGI object my $cgi = new CGI; sub new { my $class = shift; return bless {}, $class; } sub htmlHead { my $title = shift; print $cgi->header("text/html"); print $title; print "<br>"; } 1;

and here is the code that calls the module:

#!/usr/bin/perl -w use strict; use CGI qw(:standard escape escapeHTML); use DBI; use htmlCode2; use CGI::Carp qw(fatalsToBrowser); #Create new CGI object my $cgi = new CGI; #Create new htmlCode object my $htmlCode = new htmlCode2; $htmlCode->htmlHead("Title Test"); print "Test Text";

when I access it through my browser I get this:

htmlCode2=HASH(0x9cfbb3c)
Test Text

Thanks in advance for any help,
Rich

Replies are listed 'Best First'.
Re: Passing a variable to a module
by JavaFan (Canon) on Oct 31, 2008 at 01:35 UTC
    If you call a subroutine as a method (which is what you are doing her), the first argument will be the object or class name. Since you're calling it on an object, the object will be the first argument. The object is a blessed hash, and that's exactly what you print out. You want to print the second argument, not the first.
      The resulting code is:
      sub htmlHead { my $self = shift; # <------ my $title = shift; print $cgi->header("text/html"); print $title; print "<br>"; }
        I actually ended up using:

        sub htmlHead { my $title = $_[1]; print $cgi->header("text/html"); print $title; print "<br>"; }

        Thank you both for your help
        Rich