in reply to How to make a variable in hard call.

This is probably the simplest way:
sub inputPin { my $s = sprintf("Device::BCM2835::RPI_V2_GPIO_P1_%02d", $_[0]); return (\&$s)->(); } inputPin(7); inputPin(6); etc..

Replies are listed 'Best First'.
Re^2: How to make a variable in hard call.
by ikegami (Patriarch) on May 10, 2023 at 03:12 UTC

    First of all, it would be simpler to avoid misleading the user by using a hack to circumvent strictures.

    sub input_pin { my $name = sprintf( "Device::BCM2835::RPI_V2_GPIO_P1_%02d", $_[0] ) +; no strict "refs"; return $name->(); }

    But consider the following version:

    my @input_pin; for ( @Device::BCM2835::EXPORT_OK ) { next if !/^RPI_V2_GPIO_P1_(\d+)\z/; my $pin = 0 + $1; my $val = do { no strict "refs"; "Device::BCM2835::$_"->() }; $input_pin[ $pin ] = $val; }

    This version allows us to do

    $input_pin[3] $input_pin[5] $input_pin[7] ...

    instead of the slower

    input_pin(3) input_pin(5) input_pin(7)

    So what if it's not the simplest?


    Update: The point of the first half is that using no strict version is simpler, but it originally said the opposite! woops. And sprintf was misspelled.