0

我正在尝试在 Perl 等式中使用可能的变量。

例如:

#!/usr/bin/perl -w

$a = "yellow";

$b = "orange";

$c = "col1fl0ur";

$c = $a + $b;

print "$a + $b = $c \n";

我希望能够说明每个变量$a, $b,的值$c,然后能够说

$a + $b = "col1fl0ur"

你可能会问;重点是什么?只需打印出来col1fl0ur,但我也希望能够使用更多变量,例如在这种情况下:

#!/usr/bin/perl -w


###values###
$a = "yellow";

$b = "orange";

$c = "col1fl0ur";

$d = "derp";

$e = "oplo";

$f = "qwerty";


###defining the equation###
$c = $a + $b;

$d = $a + $c;

$f = $d + $c;


###Printing###
print "$a + $b = $c \n";
print "$a + $c = $d \n";
print "$d + $c = $f \n";
4

3 回答 3

1

如果您解释了您的真正问题,这将有很大帮助,但这样的事情可能会有所帮助。

请注意,您永远不应该在实时代码中使用$a$b,因为它们是保留的变量名。

use strict;
use warnings;

my ($a, $b, $c, $d, $e, $f) = qw( yellow orange col1fl0ur derp oplo qwerty );

### defining the equation ###

my %sum;
$sum{$a}{$b} = $c;
$sum{$a}{$c} = $d;
$sum{$d}{$c} = $f;

### Printing ###

for my $pair ([$a, $b], [$a, $c], [$d, $c]) {
  my ($p1, $p2) = @$pair;
  printf "%s + %s = %s\n", $p1, $p2, $sum{$p1}{$p2};
}

输出

yellow + orange = col1fl0ur
yellow + col1fl0ur = derp
derp + col1fl0ur = qwerty

如果你想$b + $a和那一样,$a + $b你必须明确地说出来。例如,

$sum{$a}{$b} = $c;
$sum{$b}{$a} = $c;
于 2013-10-12T15:20:33.163 回答
1

您可以使用 Overload pragma.. 您可以按如下方式创建一个新包:

package Tst;
use overload "+" => \&myadd;

sub new {
    my $class = shift;
    my $value = shift;
    return bless \$value => $class;
}

sub myadd {
    my ($x, $y) = @_;
    $x = ref($x) ? $$x : $x;
    $y = ref($y) ? $$y : $y;
    my $value = '';
    if ($x eq 'yellow' and $y eq 'orange'){
        $value = 'col1fl0ur';
    }
    return $value;
}
1

然后在你的主程序中,你可以做你喜欢的事情:

use Tst;

my $a = Tst->new('yellow');
my $b = Tst->new('orange');

my $c = $a + $b;

say $c;

这打印出来col1fl0ur

于 2013-10-12T16:51:04.000 回答
1

与其为 Perl 变量(等)赋值,不如$a, $b, $c考虑创建一个适合您目的的数据结构(无论它们是什么!?!)。鲍罗丁的回答朝着这个方向迈出了一部分。

这个例子把这个想法更进一步:你的“数学”系统中的术语不会链接到单个 Perl 变量;相反,它们将成为更大数据结构的组件。

use strict;
use warnings;

my %xs = (
    a => 'yellow',
    b => 'orange',
    c => 'col1fl0ur',
    d => 'foo',
    e => 'bar',
    f => 'fubb',
    g => 'blub',
);

$xs{'a + b'}         = $xs{c};
$xs{'a * c'}         = $xs{d};
$xs{'d / c'}         = $xs{f};
$xs{'a + b - d + f'} = $xs{g};

printf("%15s = %s\n", $_, $xs{$_}) for sort keys %xs;

输出:

              a = yellow
          a * c = foo
          a + b = col1fl0ur
  a + b - d + f = blub
              b = orange
              c = col1fl0ur
              d = foo
          d / c = fubb
              e = bar
              f = fubb
              g = blub
于 2013-10-12T17:52:00.940 回答