Search code examples
perlreferenceimagemagicksubroutine

Perl: modify an ImageMagick object in a subroutine


I'm using Perl (5.16) and ImageMagick (6.8.8). I'd like to send a new ImageMagick object to a subroutine by reference and modify the object there, but I get "Can't call method "Read" on unblessed reference". Obviously, I'm not treating the object properly in the subroutine. Can anyone help? Thanks.

my $im=Image::Magick->new;
ModifyImage(\$im,$f);

sub ModifyImage  {
    my $im=shift;
    my $file=shift;
    my $res = $im->Read($file);
    warn $res if $res;
}

Solution

  • Your Image::Magick object $im already holds a reference to the data. You don't need to take a reference to the variable, and your call should look like

    ModifyImage($im, $f);
    

    And I would write the subroutine like this

    sub ModifyImage {
        my ($im, $file) = @_;
    
        my $res = $im->Read($file)
        warn $res if $res;
    }
    

    to make it more concise, and to make it clear that $im and $file are parameters.