How do you use dispatch tables with a short example?

In Perl, a dispatch table is a powerful construct that allows you to associate keys with specific subroutines (functions). This approach helps organize your code and makes it easier to manage function calls dynamically based on some criteria.

Here’s a short example illustrating the use of a dispatch table in Perl:

# Define a dispatch table my %dispatch_table = ( 'add' => \&add_numbers, 'subtract' => \&subtract_numbers, 'multiply' => \&multiply_numbers, ); # Define the subroutines sub add_numbers { my ($x, $y) = @_; return $x + $y; } sub subtract_numbers { my ($x, $y) = @_; return $x - $y; } sub multiply_numbers { my ($x, $y) = @_; return $x * $y; } # Usage my $operation = 'add'; # This can come from user input or other sources my $result = $dispatch_table{$operation}->(5, 3); # Calls add_numbers(5, 3) print "Result: $result\n"; # Prints: Result: 8

Perl dispatch table subroutine function call