CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
passing hash from subroutine to subroutine

 



alferic
Novice

Mar 20, 2014, 6:25 AM

Post #1 of 2 (2376 views)
passing hash from subroutine to subroutine Can't Post

 
hello Gurus,

I need your expertise to help me understand and help me solve my issue. My perl script is too long to post it here so I will try to give a summary shall I say. Below is the overview of the script.

#! /usr/bin/perl

require my_module.pm;

my %hash1 = ();
my %hash2 = ();

&create_hash();
&post_parse();
&trappings();
&parse_final_var();

sub create_hash
{
### %hash is created here by parsing the values inside a file handle,
}

sub trappings
{
### if %hash1 and %hash2 is empty, program exits here
}

sub parse_final_var
{
### %hash1 and %hash2 is manipulated here
}
–------------------------------------------------------------------
#### inside the my_module.pm

sub post_parse
{
### Store %hash1 to %hash2

}
–-------------------------------------------------------------------

The problem here is that when %hash1 is stored to %hash2 in the my_module.pm, the subroutine traps it telling that %hash2 is empty and exits.

If I change the hash declaration from “my %hash1 & my %hash2” to “our %hash1; our %hash2” the script run correctly.

My question is, would it be possible to just declare the hashes using “my” instead of “our” and make the program run correctly?


FishMonger
Veteran / Moderator

Mar 20, 2014, 6:55 AM

Post #2 of 2 (2373 views)
Re: [alferic] passing hash from subroutine to subroutine [In reply to] Can't Post

First, you're missing 2 very important use statements which should be in every script you write.

Code
use strict; 
use warnings;

Or, if you're using one of the newer versions of perl, which you should be doing, you can do this instead which loads those pragmas as well as several other commonly needed modules.

Code
use Modern::Perl;


Next, don't use '&' when calling subs unless you know, understand and want its side affects.

My answer to your question is to not use the our keyword, which creates a global var, unless that var really does need to be global. Vars almost never need to be global.

Your incomplete code snippet doesn't provide enough info on what you're trying to accomplish to be able to show you how to fix it without doing a lot of guess work on my part.

What does your module supposed to do?

How does it relate to your sample code?

It would be best to post a short but complete test script and module which demonstrates your problem.

If you have, as I assume, vars declared in the module which you want to use in the script, then those vars normally should be exported.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives