in reply to trouble with evaluate

Assuming you have use strict on like you should...

Then the following would allow you to access package variables declared with our (not with my).

our $var1; our $var2; sub get_var{ my ($self, $var_name) = @_; no strict 'refs'; return ${"$var_name"}; }

I'm really not sure why you would want to do that though.

Replies are listed 'Best First'.
Re^2: trouble with evaluate
by genghis (Novice) on Apr 09, 2011 at 00:14 UTC

    "Thanks wind, but I was trying to avoid "our" because of all of the dire warnings I have read about using it."

      What "dire warnings" about using our?

      Also, you claim that the below parse function works. How does it actually "work"? What do you believe that you're saving in $self->{$var1} and how are you planning on using it?

      my $var1; my $var2; my $var3; #set values -- this part works sub parse{ ... $self->{$var1} = 'a'; $self->{$var2} = 'b'; $self->{$var3} = 'c'; ... }

      If you're doing true Object Oriented programming, I believe that what you truly want is just the following

      package parser; ... # Some constructor here ... #set values -- this part works sub parse{ ... $self->{var1} = 'a'; $self->{var2} = 'b'; $self->{var3} = 'c'; ... } sub get_var{ my ($self, $var_name) = @_; return $self->{$var_name}; }

        Thank you for the suggestion. I tried to implement it, but can't figure out what you would pass in to the get_var() method. I tried a simple string, but I always get "undef" back, even with the versions of "eval" syntax suggested by Eliya.