perlnewb4life has asked for the wisdom of the Perl Monks concerning the following question:

Hello i need some help understanding OOP Perl using Moose; i have created a class whose attributes are all subtypes , for validation purposes. Example code :

package InputData; use Moose; use InputDataSubtypes qw(subtype); has 'attribute' => ( is => 'rw', isa => subtype, required => 1, ); 1;

I want to pass InputData to a subroutine , then use InputData->attribute , as if i would be using a getter in Java. The InputData->attribute is used to do a query on a mysql database using prepared statement:

package Operations; use DBI; use DBConnection; use InputData; use Moose; sub querryDatabase() { my($inputData) = @_; my $query = 'select stuff from myTable where attribute = ?'; my $dataSource = DBConnection->getConnection(); my $preparedStatement = $dataSource->prepare($query); $preparedStatement->execute($inputData->attribute) or die "SQL Erro +r: $DBI::errstr\n"; while (my @row = $preparedStatement->fetchrow_array){ print "@row\n +"; } $preparedStatement->finish(); $dataSource->disconnect(); } 1;

i call the subroutine like this :

package MainScript; use strict; use warnings; use v5.22; use InputData; use Operations; use Moose; my $myInputData = InputData->new( { attribute => 'caller', } ); #here i do the sub call; Operations->querryDatabase($myInputData);

But i get the error Can't locate object method "attribute" via package "Operations" at ....Operations.pm line 28. Any help would be greatly appreciated, also sorry if i didn't format the question appropiatly

Replies are listed 'Best First'.
Re: calling sub with object as param
by stevieb (Canon) on Sep 01, 2015 at 13:44 UTC

    Welcome to the Monastery!

    You're creating an object prior to the sub call with a hash reference parameter, which has a key named attribute.

    In the Operations package, you're trying to call attribute as a method (subroutine), but that's not what attribute is.

    Change this:

    $preparedStatement->execute($inputData->attribute)

    ...to this (note the curly braces around attribute, which denotes it as a hash reference key):

    $preparedStatement->execute($inputData->{attribute})

    and see if that helps get you where you want to be.

    -stevieb

      I think the OP isn't handling the class name as the first parameter in the method.

        hello, thank you for your quick response , can you please give some sample code so that i can better understand what you mean ? i am just starting to learn perl.