2

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?

nanocv
  • 2,227
  • 2
  • 14
  • 27
  • 2
    Please don't use `new MyClass`. This is not Java. `new` is not a keyword. `MyClass->new()` will save you much potential confusion in the future. – Dave Cross Nov 02 '16 at 15:32
  • 1
    Ok! I edited the question to better illustrate the example. Thanks for the tip @DaveCross – nanocv Nov 02 '16 at 17:03

1 Answers1

5

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.

toolic
  • 57,801
  • 17
  • 75
  • 117
  • 6
    @nanocv: I find the block version of `map` makes things clearer - `map { $myClass->displayChar($_) } @charArray;`. Also, if you're not doing something with the list returned by `map`, you should be using `foreach` instead` - `$myClass->displayChar($_) foreach @charArray;` – Dave Cross Nov 02 '16 at 15:34