Search code examples
perlmap-functioninstance-method

Perl map using object method


I have a Perl Module file MyClass.pm 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";
}

1;

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

#!/usr/bin/perl
use strict;
use warnings;

use MyClass; 
my $myClass = MyClass->new();

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

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

When I call the displayChar 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 MyClass.pm 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?


Solution

  • 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.