nanocv nanocv - 11 months ago 60
Perl Question

Perl map using object method

I have a Perl Module file
with a very basic class definition.

use strict;
use warnings;

package MyClass;

sub new {
my $this = shift;
my $self = {};
bless $self, $this;
return $self;

sub displayChar{
my $self = shift;
my $char = shift;
print $char . "\n";


Also I have a
file that creates an instance of MyClass.

use strict;
use warnings;

use MyClass;
my $myClass = new MyClass;

$myClass->displayChar('a'); # This line works right

my @charArray = ('a', 'b', 'c');
map($myClass->displayChar, @charArray);

When I call the
method it works right, but when I try to use map function with that method it gives me this error three times (once per array item, I guess):

Use of uninitialized value $char in concatenation (.) or string at line 16.

Am I using map function in a wrong way? Or maybe it's not possible to use an object method as first param?

Answer Source

You need to pass a value to your displayChar method:

map($myClass->displayChar($_), @charArray);

map locally sets the $_ variable to each value of your array.