nasatome nasatome - 6 months ago 19
Perl Question

how to get the number of items in a list within a bless in PERL

I am a beginner in PERL, I need to get the size of an array

soap consultation code is as follows

my @params = ( SOAP::Data->name(user => '2355'),
SOAP::Data->name(psw => '2355')
);

my $soap = SOAP::Lite
-> uri('https://service.example.com')
-> on_action( sub { join '/', 'https://service.example.com', $_[1] } )
-> proxy('https://service.example.com/service.php?wsdl');

my $method = SOAP::Data->name('GetAll')
->attr({xmlns => 'https://service.example.com'});

my @products = $soap->call($method => @params)->result;


this returns me

$VAR1 = bless( {
'manufacturer' => [
'Microsoft',
'Lenovo',
'HP'
],
'dispach' => [
'0',
'51',
'0'
],
'date_end' => [
0,
0,
'2016-06-30'
],
'sku' => [

'R23649C ',
'DW47-03 ',
'YDG-016 '
],
'tree' => [
'MS-OPEN ',
'LENOVO-AIO ',
'HP ACADEMIC '
]
}, 'parametros_salida');


I can access the data with

print $products->{"sku"}[0];
print $products->{"manufacturer"}[0];
print $products->{"manufacturer"}[1];


but I can not count as the result of my call SOAP only return a single variable Dumper($products) therefore I can not get the array size.

I've tried

my @products2 = $products
print 0 + @products2;
print scalar(@products2);
print scalar $products;

Answer

EDIT: As others have pointed out, for this specific example - when your hash reference is in fact a blessed reference (that is to say, an object), you should be using the class's API to obtain its members, not digging into the internals of the objects. What follows is a generic answer for a non-blessed reference.


$products and @products are two entirely unrelated variables. They have nothing to do with one another.

Assuming that $products is the variable that you passed to Data::Dumper to obtain that output, then $products is a reference to a hash. It is not an array, so I'm not sure what you mean when you ask for the "array size".

You can find out how many keys are in the hash that $products references by using:

my $key_count = keys %{$products};

Or if you wanted the size of the one of the arrays inside the hash that $products references, such as manufacturer, you can do:

my $size = @{$products->{manufacturer}};

You can learn more about references and data structures in perl at: http://perldoc.perl.org/perlref.html and http://perldoc.perl.org/perldsc.html

Comments