School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 300,419 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,501 people online right now. Registration is fast and FREE... Join Now!




Using and renaming same variables/hash within different subroutines,

 

Using and renaming same variables/hash within different subroutines,

Sun751

24 Jun, 2009 - 12:14 AM
Post #1

D.I.C Head
**

Joined: 11 Dec, 2008
Posts: 57



Thanked: 1 times
My Contributions
I am writing Perl script for my project, where I am passing same variable to different sub routine with different name so that it won’t collide with same variable within another subroutine,

Though, the variable holds same value due to continuous renaming in different subroutine its getting bit confusing and looks like bit of mess , for example,
CODE

my (%resource,$portoffset);

initialize(\%resource,$portoffset);
consolidate(\%resource, $portoffset);
dispatch(\%resourcel,$portoffset);


sub initialize
{
    my ($HRI_resource,$I_portoffset) = @_;
}

sub consolidate
{
  my  ($HRC_resource, $C_portoffset)= @_;
}

sub dispatch
{
my  ($HRD_resource, $D_portoffset)= @_;
}

Any one have any suggestion regarding this? Please let me know.

Cheers


User is offlineProfile CardPM
+Quote Post


dsherohman

RE: Using And Renaming Same Variables/hash Within Different Subroutines,

24 Jun, 2009 - 05:42 AM
Post #2

D.I.C Head
**

Joined: 29 Mar, 2009
Posts: 184



Thanked: 35 times
My Contributions
Lexically-scoped variables (i.e., those defined using "my") don't exist outside of the block where they're defined, so you don't actually need to use different names. Running the code:
CODE
#!/usr/bin/perl

use strict;
use warnings;

first();
second();

sub first {
  my $x = 1;
  print "first: $x\n";
}

sub second {
  my $x;
  print "second: $x\n";
}

produces the output
CODE

first: 1
Use of uninitialized value in concatenation (.) or string at foo.pl line 16.
second:


As you can see, the $x in second() is uninitialized even though $x was set to 1 in first(). They are completely separate variables which do not interact with each other at all, despite having the same name, because each is confined to a different scope.

For a more thorough discussion of the topic, see MJD's Coping with Scoping and, in particular, the "Lexical Variables" section.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/7/09 11:55PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month