如何在perl中显示变量的名称以及变量的值?

时间:2019-11-12 16:40:23

标签: perl subroutine declare

要诊断或调试我的Perl代码,我想轻松地显示变量名称及其值。在 if abs(destination - origin) <= 180: return (destination - origin) else: degrees = 360 - abs(destination - origin) if destination < 180: return degrees else: return -degrees 中,键入以下内容:

bash

#!/bin/bash dog=pitbull declare -p dog 中,考虑以下脚本perl

junk.pl

如果我们调用此脚本,我们将获得

#!/usr/bin/perl
use strict; use warnings; 
my $dog="pitbull";
my $diagnosticstring;
print STDERR "dog=$dog\n";
sub checkvariable {
    foreach $diagnosticstring (@_) { print "nameofdiagnosticstring=$diagnosticstring\n"; }
}
checkvariable "$dog";

但是,相反,当调用子例程bash> junk.pl dog=pitbull nameofdiagnosticstring=pitbull bash> 时,我希望打印以下内容:

checkvariable

这将使编码更容易且更不容易出错,因为不必两次键入变量名称。

4 个答案:

答案 0 :(得分:3)

您可以使用PadWalker做类似的事情(需要从CPAN安装)。但这几乎肯定比您想要的复杂得多。

#!/usr/bin/perl

use strict;
use warnings; 
use PadWalker 'peek_my';

my $dog="pitbull";
print STDERR "dog=$dog\n";
sub checkvariable {
  my $h = peek_my(0);
  foreach (@_) {
    print '$', $_,'=', ${$h->{'$'. $_}}, "\n";
  }
}
checkvariable "dog";

答案 1 :(得分:3)

Data::Dumper::Names可能就是您想要的。

#! perl

use strict;
use warnings;

use Data::Dumper::Names;

my $dog = 'pitbull';
my $cat = 'lynx';
my @mice = qw(jumping brown field);

checkvariable($dog, $cat, \@mice);

sub checkvariable {
    print Dumper @_;
}

1;

输出:

perl test.pl

$dog = 'pitbull';
$cat = 'lynx';
@mice = (
          'jumping',
          'brown',
          'field'
        );

答案 2 :(得分:2)

(不是答案,是带格式的注释)

checkvariable子项仅接收一个值,并且没有(简单或可靠)的方法来找出什么变量持有该

这就是为什么Data :: Dumper强制您将varnames指定为字符串的原因:

perl -MData::Dumper -E '
  my $x = 42;
  my $y = "x";
  say Data::Dumper->Dump([$x, $y]);
  say Data::Dumper->Dump([$x, $y], [qw/x y/])
'
$VAR1 = 42;
$VAR2 = 'x';

$x = 42;
$y = 'x';

答案 3 :(得分:0)

通常有以下帮助

use strict;
use warnings;

use Data::Dumper;

my $debug = 1;

my $container = 20;
my %hash      = ( 'a' => 7, 'b' => 2, 'c' => 0 );
my @array     = [ 1, 7, 9, 8, 21, 16, 37, 42];

debug('container',$container) if $debug;
debug('%hash',  \%hash)       if $debug;
debug('@array', @array)       if $debug;

sub debug {
    my $name  = shift;
    my $value = shift;

    print "DEBUG: $name [ARRAY]\n", Dumper($value) if ref $value eq 'ARRAY';
    print "DEBUG: $name [HASH]\n",  Dumper($value) if ref $value eq 'HASH';
    print "DEBUG: $name = $value\n"                if ref $value eq '';
}

但是为什么不在内置调试器下运行perl脚本呢?选项 -d

The Perl Debugger

相关问题