Joseph Joseph - 7 months ago 11
Perl Question

How to get the content of an argument to a Perl subroutine

I want a sub that takes an argument and prints the argument supplied in its original form along with the evaluation of the argument.

In this case, the evaluation of argument is easy, that's the default! It's getting the actual input in its original form that is difficult.

use strict;
use warnings;

sub echo {
my ($input) = @_;
# print "5 + 10 =";
print $input;
print "\n";
}

echo 5 + 10;


This will output
15
.

I want it to output
5 + 10 = "15"

Answer
sub echo {
    my ($expr, $result) = @_;
    print "$expr = $result\n";
}

echo '5 + 10', 5 + 10;

or

sub echo {
    my ($expr) = @_;
    my $result = eval($expr);
    die $@ if $@;
    print "$expr = $result\n";
}

echo '5 + 10';