User Control Panel
Advertisements

HELP US, HELP YOU!

Hashes and Hashes

 
Post new topic   Reply to topic    Bot Depot Forum Index -> Perl
View unanswered posts
Author Message
davidk
Senior Member
Senior Member


Joined: 14 Feb 2004
Posts: 195
Location: United Kingdom, Europe, Earth, Solar system, The Milky Way, The Universe, the 3rd Dimension.
Reputation: 31.1Reputation: 31.1Reputation: 31.1

PostPosted: Wed Mar 16, 2005 9:30 pm    Post subject: Reply with quote

Can I pass a variable hash ($this) to a sub that expects a hashref (%this)?
Back to top
Mojave
Almost An Agent
Almost An Agent


Joined: 01 Nov 2003
Posts: 1434

Reputation: 66.4

PostPosted: Wed Mar 16, 2005 9:48 pm    Post subject: Reply with quote

You have those backwards. $this is a hashref, %this is a hash. % is for hashes, @ is for arrays and $ is for scalars. A reference is always a scalar so it needs $.

You can pass a hash or a hashref into a sub, but the sub needs to be expecting one or the other. You can dereference a hashref by using %$hashref, you can make a hashref out of hash by using \%hash. So if you know what type of variable a sub is expecting, you can convert (also know as casting) one to the other.

Usually, you want to pass references around, because they don't make copies of the entire data structure. For instance, if you have a hash with 5000 items and you pass it as a hash to a sub, the sub has to make a complete copy. But if you pass it by reference, the sub just makes a copy of the reference.

There is a way to check if the value passed to a sub is a reference or not, but I'll leave that for another time.
Back to top
Display posts from previous:   
Post new topic   Reply to topic    Bot Depot Forum Index -> Perl All times are GMT
Page 1 of 1

 



Protected by phpBB Security phpBB-TweakS
phpBB Security Has Blocked 9 Exploit Attempts.
Antispam Captcha Mod by phpbb-security.com
Powered by phpBB © 2001, 2005 phpBB Group