Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with passing hashes by reference

Status
Not open for further replies.

JJ1

Programmer
Apr 19, 2001
104
GB
I'm trying to write a script to send an email containing a traffic monitoring graph from some network management software (MRTG).

Could anyone help me with passing a hash by reference please?

This is my code:
Code:
#Main#

#Get info
@mails = get_info()

#Mails is an array of hashes
#Pass by ref
get_html ( \$mails[$i]{'html'} );


sub get_info{
    ...etc...
    #store the filepath of the html page to send
    $mail{'html'}{'file_loc'} = $content;
    ...etc...
}


#Open HTML file#
sub get_html{
   my ( $html_hash ) = @_;	
   #Open HTML file specified in hash table
[red]
Code:
  open ( HTML, [red]${$html_hash{'file_loc'}} );
[/red]
Code:
   ...etc...

}


The line in red above is where Perl chokes and I see this error:

[red]
Code:
"Global symbol "%html_hash" requires explicit package name at email2.pl line 140."
[/red]

Line 140 is where I try to read the values in the hash table which I have just passed by ref.

Could anyone show me how to read arrays of hashes after they have been passed by reference please? I can paste the whole program if necessary.

Many thanks,

James.
 
If you have a hash
[tt] my %hash;[/tt]
you can pass it's ref to a sub
[tt] foo( \%hash );[/tt]
which would grab it as an argument
[tt] sub foo {
my $hashref = $_[0];[/tt]
and use it thus
[tt] @keys = keys %$hashref;
$someval = ${$hashref}{somekey};[/tt]
or, prettier
[tt] $someval = $hashref->{somekey};[/tt]
and even
[tt] @somevals = ${$hashref}{@somekeys};[/tt]




Check out the perlref and perlreftut man pages.


Yours,

"As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs."
--Maurice Wilkes
 
First, don't reinvent the wheel. Use something like the Mail::Mailer module. Example:

Code:
my $mailer = Mail::Mailer->new('sendmail');
$mailer->open({
   From    => 'foo@example.com',
   To      => 'bar@baz.com',
   Subject => 'subject text'
});
print $mailer "your body text";
$mailer->close();

As for the global symbol error, why not just open like this:

Code:
open HTML, &quot;<$html_hash{'fileloc'}&quot;;

--
Andy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top