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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pointer to a Hash

Status
Not open for further replies.

redd99

Programmer
Joined
May 12, 2009
Messages
1
Location
CA
What is the difference between setting a hash like this:
Code:
$fooref->bar('cat');

and like this:
Code:
$fooref->{bar} = 'dog';

Apparently each statement is setting an entirely different hash.
Which is the proper way to do it?

And also if I were to concatenate the hash with a string using double quotes how would i do it?

I tried:
Code:
print "This is a $foo->bar";

But perl does not interpret the "->" symbol.

I tried this:
Code:
print "This is a $$foo{bar}";
which works but how do I get perl to interpret the "->" symbol?

Code:
use Class::Struct;

struct foo =>
{
  bar => '$'
};

my $fooref = foo->new();

$fooref->bar('cat');
$fooref->{bar} = 'dog';

print $fooref->bar;
print "\n";
print $fooref->{bar};
 
The format "$fooref->bar('cat')" isn't a hashref. Instead, $fooref is a reference to an object named foo, which has a subroutine named "bar", and presumably it lets you get/set the value of an internal private hashref by using the subroutine interface.

It's like this:
Code:
package foo;

sub new {
   return bless {}, "foo";
}

sub bar {
   my ($self,$value) = @_;
   if (defined $value) {
      $self->{bar} = $value;
   }
   return $self->{bar};
}

package main;

my $fooref = new foo();
$fooref->bar("cat");
print $fooref->bar();

The format "$fooref->{bar}" is a proper hash reference like normal.

So the first one is a subroutine, which hides a data structure behind it, the second is a data structure.

As for the arrow syntax: you can't call subroutines/methods on an object inside quotes, but you can get values out of a hashref.

Code:
# method call:
print "the value is ", $fooref->bar(), ".\n";
# hashref fetch:
print "the value is $fooref->{bar}.\n";

Perl recognizes the -> in your variables as long as everything is valid, i.e. the arrow only works to get members out of a referenced data structure. You can't call methods inside of quotes by using arrows, though.

Cuvou.com | My personal homepage
Code:
perl -e '$|=$i=1;print" oo\n<|>\n_|_";x:sleep$|;print"\b",$i++%2?"/":"_";goto x;'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top