簡體   English   中英

如何在RedHat上使用核心Perl打印變量及其值?

[英]How can I print a variable and its value with just core Perl on RedHat?

我正在嘗試在Perl中創建一個簡單的小子,最好不要使用標准RedHat linux發行版中沒有的任何模塊。 換句話說,越便攜越好,因為我不能總是控制我正在使用的系統環境。顯而易見的問題是將變量傳遞給子程序,以便可以使用原始變量名和值。 我可以得到一個或另一個,但無法弄清楚如何做這兩個沒有更復雜的子調用輸入,如下所示。 我可以傳遞一個字符串和一個引用,但這幾乎就像在本地打印簡單一樣混亂:

print "\$A = $A\n"; 

還存在潛在的范圍問題,但一次只能邁出一步。 我現在想也許這不是那么簡單。

(是的,這是我正在尋找的絕對懶惰的程序員代碼)

示例偽代碼:

my $A = 1;
my $secondVar = "something new";
my $XXX = 12345;

# Print a listing of the variables of interest in a nice easy to read listing
# with a minimum of typing. 

printVars( $A, $secondVar, $XXX ); 

# Note I could settle for passing by reference \$A but no more complicated than this in
# the sub call. This is just a little utility sub to use to double check variables while
# coding something new.

輸出:

$A = 1
$secondVar = something new
$XXX = 12345

一個粗略的SUB:

sub printVars {
    my @ListOfVars = @_;
    my $i;
    my ($theVarName, $theVarValue);

    for( $i=0; $i<@ListOfVars; $i++) {
       $theVarName = ??;  # This is where things break down.
       $theVarValue = $ListOfVars[$i];
       print "$theVarName = $theVarValue\n";
    }
}

感謝您提供的任何幫助..

享受.. - 布萊恩

如果使用Paul Tomblin和john建議的變量名稱的方法是可以接受的,您可能需要引入Data::Dumper模塊以便能夠打印出數據結構。

Data::Dumper長期以來一直是標准Perl5發行版的一部分(我剛剛在CPAN上驗證過它已經在5.6,5.8和5.10中)。 如果您的操作系統供應商沒有以奇怪的方式將其分開,則無需擔心Data::Dumper不在那里。

這真的感覺就像你在這里重新發明輪子一樣,所以我不得不問你的動機。 有許多現有的機制可以幫助您調試代碼,包括內置的調試器(參見手冊和教程的perldoc perldebugperldoc perldebugtut ),以及CPAN的巨大模塊庫。 你正在考慮建立一個初學者的任何東西已經建成,所以除非你純粹作為一種學習經驗這樣做,否則你應該使用已經可用的工具。

Data :: DumperData :: Dump是查看變量內部的常用方法,不僅僅是現在編碼的簡單字符串,還有深度和復​​雜的數據結構。 Data :: Dumper是許多標准Perl安裝的一部分,但CPAN上分發的任何內容都可以安全依賴,因為它可以輕松安裝在您可能遇到的任何系統上。

我不認為這可以在沒有求助於PadWalker的情況下對詞法變量進行,所以你可能需要安裝它。 假設你可以,這是一個工作解決方案,允許最小的調用站點語法。

use PadWalker qw/peek_my peek_our/;
use Data::Dumper;
$Data::Dumper::Indent = 0; # or however pretty you want

sub inspect {
    my $my  = peek_my  1;
    my $our = peek_our 1;

    for (split(/\s+/ => "@_")) {
        my $val = $$my{$_} || $$our{$_} 
                           || die "$_ not found";
        print Data::Dumper->Dump(
            /^\$/ ? ([$$val], [$_])
                  : ([ $val], ['*' . substr $_, 1])
        ) . "\n";
    }
}

sub foo {
    my $bar = shift;
    inspect '$bar';
}

{ # closed scope
    my $x = 'hello, world!';
    my $y;
    my @z = 1 .. 10;
    our %global = (a => 1, b => [1 .. 3]);
    my $ref = \%global;

    inspect '$x $y @z %global $ref';  # qw/.../ can be used also
    foo;
    foo $x;
}

打印出來

$x = 'hello, world!';
$y = undef;
@z = (1,2,3,4,5,6,7,8,9,10);
%global = ('a' => 1,'b' => [1,2,3]);
$ref = {'a' => 1,'b' => [1,2,3]};
$bar = undef;
$bar = 'hello, world!';

您可以將變量名稱作為標量傳遞,然后使用引用來打印出值。 來自perlref:

1.  $name = "foo";
2. $$name = 1; # Sets $foo
3. ${$name} = 2; # Sets $foo
4. ${$name x 2} = 3; # Sets $foofoo
5. $name->[0] = 4; # Sets $foo[0]
6. @$name = (); # Clears @foo
7. &$name(); # Calls &foo() (as in Perl 4)
8. $pack = "THAT";
9. ${"${pack}::$name"} = 5; # Sets $THAT::foo without eval

傳入變量名稱列表,然后將其打印出來

foreach $varname (@list)
{
   print "$varname = $$varname\';
}

實際上,要考慮它,這也不會起作用,因為$$將無法工作,因為該變量將不會被子所知。 我不認為你能做你想做的事情,除了把所有變量名和值放入哈希並用Data :: Dumper轉儲它們。 通常在這一點上我會刪除這個答案,但其他幾個人已經引用了它,所以我不會。

use Data::Dumper;
print Dumper({"a" => $a, "cVar" => $cVar});

會產生類似的東西:

$VAR1 = {
          'a' => 'foo',
          'cVar' => 'this is cVar'
        };

請參見如何將變量用作變量名稱? 關於使用變量作為變量名稱的觀點。 否則你必須使用john和Paul Tomblin建議的參考文獻。

沒有子,但我推薦Smart::Comments 這很簡單:

use Smart::Comments;
### $A

$A將在所有被示出它的光彩,如果1)它不具有動態循環(如一些的Win32 :: OLE對象做),或者如果2)它不是一個“內向外對象”,這是一個指針,指向數據的關鍵,而不是數據本身。 輸出比Data::Dumper更具可讀性(它在幕后使用Data::Dumper ,因此DD全局變量可用,如$Data::Dumper::Deparse (在鏈表的底部),用於打印出局

當你不想打印出來時,只需注釋掉use語句。 然后,他們只是評論。

它也很便攜。 我只是簡單地將Text :: Balanced和Smart :: Comments從我的PC移植到了AIX盒子里。 完成。

# A sub to print the value of any variable, scalar, array, or hash
sub strv
{ # edit structured things as a string for debugging
  my ($v,$d) = @_;
  my $s = '';

  $d = 0 if not defined $d;

  if (not defined $v)
  {
    $s.= (' 'x$d)."N";
  }
  elsif (ref($v) eq 'SCALAR')
  {
    if (! defined $$v)
    {
      my $null = 'NULL';
      $v = \$null;
    }
    $s.= (' 'x$d)."S:$$v";
  }
  elsif (ref($v) eq 'ARRAY')
  {
    $s.= (' 'x$d)."A:(";

    my $c = '';
    my $x = 0;

    foreach my $a (map(strv($_,0),@{$v}))
    {
      $s.= "$c$x:$a";
      $c = ',';
      $x++;
    }
    $s.= ")";
  }
  elsif (ref($v) eq 'HASH')
  {
    $d++;
    $s.= "\n" if $s ne '';
    while( my ($k, $x) = each %{$v} ) {
      $s.= (' 'x$d)."H:".strv($k,$d+1).": ".strv($x,$d+1)."\n";
    }
    $s = substr($s, 0, -1);
  }
  elsif (ref($v))
  {
    $s.= ref($v);
  }
  $s.= (' 'x$d).'"'.$v.'"' if ref($v) eq '';
  return $s;
} # sub strv

這里的記錄是一個實際解決方案的例子,正如你們幾個人使用Data :: Dumper所建議的那樣。 希望它可以幫助任何人輕松地尋找一個簡單的sub到漂亮的打印變量。 謝謝你們!!

#!/usr/bin/perl -w
use strict;
use warnings;
use Data::Dumper;

my @myArray = qw ( a b c d e f g h i j k );

# Showing Difference between shift and pop and what happens to @myArray
my ($A, $B, $C, $D,);

$A = shift @myArray;
$B = pop   @myArray;
$C = shift @myArray;
$D = pop   @myArray;

# prtVar() usage is close to original desired simplicity 
# only needed to add the qw() 

prtVar(qw ($A $B $C $D));

sub prtVar
    {
    my (@vars) = @_;
    my $vname;

    foreach $vname (@vars)
        {
        print Data::Dumper->Dump([eval($vname)], [$vname]);
        }
    }

輸出:

$A = 'a';
$B = 'k';
$C = 'b';
$D = 'j';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM