0

I try to create an array of perl structures. Each struct contains two scalars and a hash. Later I want to find an item of the array, get the hash and find a scalar inside the hash.

I can find the item inside the array and get the scalars. But I don't know hot to correctly get the hash and a value inside it.

I tried with/without reference.

Thanks a lot

#hash 
%latestInfo = (
     8 => '30',
);

#struct
package Myobj;
use Class::Struct;
struct( name => '$', majorVer => '$', latestVer => '%');

$w1 = new Myobj;
$w1->name('test');
$w1->majorVer(5);
$w1->latestVer($latestInfo);

#array with all version information
@versions=($w1, ...);

sub getVersionFromMajor
{
    foreach $ver (@versions) {
        if ($ver->majorVer eq $_[0]) {
            return $ver;
        }
    }
}

#
#main
#

#ok: get version info from structures/array
local($ver) = getVersionFromMajor(5); 
local($n) = $ver->name;

#fail: get hash inside item
my $latest = \$ver->latestVer;
%lat = $ver->latestVer;

#fail: get value inside hash
local($m) = $latest{8}; 
chris
  • 398
  • 2
  • 11
  • Always include [`use strict;`](http://perldoc.perl.org/strict.html) and [`use warnings;`](http://perldoc.perl.org/warnings.html) at the top of EVERY perl script. For reasons why check [this](http://stackoverflow.com/questions/8023959/why-use-strict-and-warnings) and many other threads. – Miller Aug 06 '14 at 04:18

1 Answers1

2

This bit:

$w1->latestVer($latestInfo);

Should be:

$w1->latestVer(\%latestInfo);

%latestInfo and $latestInfo are two unrelated variables - %latestInfo is your hash, and $latestInfo is an undeclared (and thus undef) scalar. \%latestInfo is a scalar reference to %latestInfo, which is what the latestVer method (created by Class::Struct) wants you to give it.

Perl would have told you about $latestInfo not existing if you'd done use strict and declared all your variables.

Also, this bit:

%lat = $ver->latestVer;

Should be:

%lat = %{ $ver->latestVer };
tobyink
  • 13,478
  • 1
  • 23
  • 35
  • thanks a lot, I have a much better understanding now regarding perl variables; I applied both your changes, but when I print lat is still empty: print("$ver - $lat - $lat{8}"); #only shows ver – chris Aug 05 '14 at 15:25
  • That's because (even apart from the `$latestInfo` scalar variable) you have two separate hash variables called `%latestInfo`. One is defined in the `main` package, and one is used later on in the `Myobj` package. They're different variables. I'll reiterate that **Perl will tell you about these problems** if you `use strict`. – tobyink Aug 05 '14 at 17:58