0

I have few referenced subroutine and I need to pass the value to the referenced subroutine. Is there any way to do it.

   #Sample Code
   sub CreateHtmlBox {
     my ($box_type,$hash_ref) = @_;
     my %subCall = (
        'singlebox'   =>  \&CreateSingleBox   ,
        'multiplebox' =>  \&CreateMultipleBox
              );

     my $htmlCode = $subCall->($box_html);
   }

   sub CreateSingleBox {
    my ($box_type) =@_;
    #...................
    return $htmlCode;
   }

I want to call referenced subroutine and pass the reference of hash to it.

   CreateSingleBox($hash_ref)
1
  • it's not clear what value you need to pass to the subroutine you're calling. anyway, a level is missing in your example: $subCall->($box_html) should be (assuming you want to call CreateSingleBox): $subcCall{singlebox}->( $box_html ). Commented Apr 9, 2013 at 12:11

1 Answer 1

2

You have to access an specific element in the hash before you can call it as a coderef. I.e.

# WRONG! Variable $subCall does not exist.
my $htmlCode = $subCall->($box_html);

should really be

my $htmlCode = $subCall{box_type}($box_html);

The resulting code would look like this:

use strict;
use warnings;

sub CreateHtmlBox {
    my ($box_type, $hash_ref) = @_;
    my %subCall = (
        singlebox   => \&CreateSingleBox,
        multiplebox => \&CreateMultipleBox,
    );
    return $subCall{$box_type}($hash_ref);
}

sub CreateSingleBox {
    my ($box_type) = @_;
    my $htmlCode= "<p>" . $box_type->{a} . "</p>";
    return $htmlCode;
}

print CreateHtmlBox("singlebox",{a => 1})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.