【问题标题】:Debugging the following perl script on hashes在哈希上调试以下 perl 脚本
【发布时间】:2017-01-07 02:22:51
【问题描述】:

我正在编写一个 perl 脚本,该脚本在哈希中搜索姓名会返回该人的电话号码。就像在哈希中寻找一个键并返回找到的键的值一样。否则它将打印“书中未找到的名称”。当我给出哈希中存在的值时,我无法访问这些元素。我需要修改什么代码?

$namesearch="";
%phoneNumbers={"ramu"=>123,"rishi"=>456,"sai"=>789};
while($namesearch ne "END")
{
   print("Enter name to search:\n");
   $namesearch=<STDIN>;
   chomp $namesearch;
if(exists($phoneNumbers{$namesearch}))
{
     print "The phone Number of $namesearch is: ($phoneNumbers{$namesearch})\n";
 }
 elsif($namesearch eq "END")
 {
     last;
 }
 else
 {
     print "Name not found in book\n";
  }   
}

我得到的输出是:

output 
Enter name to search:
ramu
Name not found in book

【问题讨论】:

  • 总是use strict;use warnings 'all';。打开警告会给你一个线索:“在预期的偶数列表中找到参考”(指向%phoneNumbers={...}; 行)
  • 现在显示一些编译错误。

标签: perl hash


【解决方案1】:

作为一种好的做法,您应该在代码中使用 strictwarnings pragma 以便于调试。

严格

strict pragma 禁用某些 Perl 表达式 行为异常或难以调试,将它们变成 错误。此 pragma 的效果仅限于当前文件或 范围块。

警告

这个 pragma 的工作方式与 strict pragma 一样。这意味着 警告编译指示的范围仅限于封闭块。它也是 意味着 pragma 设置不会跨文件泄漏(通过使用, 要求或做)。这允许作者独立定义学位 将应用于其模块的警告检查。

我对您的代码进行了一些更改,您应该做一些事情以使其正常工作:

use strict;
use warnings;
use diagnostics;

#Always declare your variables
my $namesearch = "";

#Change your hash ref to a simple hash
my %phoneNumbers = ( "ramu" => 123, "rishi" => 456, "sai" => 789 );

while ( $namesearch ne "END" ) {
    print("Enter name to search:\n");
    $namesearch = <STDIN>;
    chomp $namesearch;
    if ( exists( $phoneNumbers{$namesearch} ) ) {
        print
          "The phone Number of $namesearch is: ($phoneNumbers{$namesearch})\n";
    }
    elsif ( $namesearch eq "END" ) {
        last;
    }
    else {
        print "Name not found in book\n";
    }
}

还可以在 perldoc 上查看有关引用 (perlreftut) 的一些说明,说明如何正确使用,因为语法会根据您使用的变量而改变,例如数组或哈希。

【讨论】:

  • 我建议不要使用全局 $namesearch,而是将其本地化:while(1){my $namesearch = &lt;STDIN&gt;;...; last if $namesearch eq 'END';...}
猜你喜欢
  • 2012-10-07
  • 2015-10-25
  • 2013-09-26
  • 2013-11-17
  • 1970-01-01
  • 2015-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多