Perl:从子程序返回哈希 [英] Perl: Return hash from subroutine

查看:30
本文介绍了Perl:从子程序返回哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了几个小时的例子,但我似乎无法理解如何做我想做的事.

I have been trying examples for hours but I can't seem to grasp how to do what I want to do.

我想从子程序返回一个哈希值,我认为引用是最好的选择.这就是它变得有点棘手的地方.我想引用像 $hash{$x} 这样的散列.我仍然是 perl 的菜鸟:/

I want to return a hash from a subroutine, and I figured a reference was the best option. Here's where it gets a bit tricky. I want to reference a hash like $hash{$x}. I am still a noob at perl :/

1.第一个问题,我使用的例子似乎表明使用 $hashTable{$login} 是可以的,我应该使用 %hashTable{$login} 还是没关系?代码如下:

1.First question, the examples I use seem to show it is ok to use $hashTable{$login}, should I be using %hashTable{$login} or does it not matter? Below is the code:

sub authUser  {
    $LocalPath = "/root/UserData";
    open(DATAFILE, "< $LocalPath");
    while( $linebuf = <DATAFILE> ) {
        chomp($linebuf);
        my @arr = split(/:/, $linebuf);
        my $login = $arr[1];        # arr[1] contains the user login names
        my $hashTable{ $login } = "$arr[0]";        #$arr[0] is account number
    }
    close DATAFILE;
    return \$hashTable{ $login };
}

然后我想测试这些数据以查看是否存在登录名,这是我的测试方法

I then want to test this data to see if a login is present, here is my test method

# test login Dr. Brule which is present in UserData
my $test = "Dr. Brule";
my $authHash = &authUser();

if ( $authHash{ $test } )  {
    print "Match for user $test";
}
else  {
    print "No Match for user $test";
}

2.如果我的 $authHash 真的是 $authHash{ $something },我对此很困惑

2.Should my $authHash be really $authHash{ $something }, I am so confused on this

经过一些阅读提示,仍在尝试但没有骰子,任何帮助将不胜感激

After some reading tips, still attempting but no dice, any help would be greatly appreciated

<小时>编辑 2:任何人都可以修改我的代码以便我可以更好地理解答案吗?对不起,我似乎根本无法让它工作,我已经尝试了几个小时,我真的很想知道正确的方法来做到这一点,我可以发布我的各种尝试,但我觉得那将是一种浪费房地产.


Edit 2: Can anyone modify my code so that I can understand the answers better? I'm sorry I can't seem to get this to work at all, I have been trying for hours and I really want to know the correct way to do this, I can post my various tries but I feel that will be a waste of real estate.

推荐答案

首先,正如 mpapec 在评论中提到的,use strict;使用警告;.这将捕获最常见的错误,包括标记您在此处询问的大多数问题(并且通常会提供有关您应该做什么的提示).

First off, as mpapec mentioned in comments, use strict; use warnings;. That will catch most common mistakes, including flagging most of the problems you're asking about here (and usually providing hints about what you should do instead).

现在回答问题 1 和 2:

Now to answer questions 1 and 2:

%hash 是整个哈希值.完整的数据结构.

%hash is the hash as a whole. The complete data structure.

$hash{key} 是散列中的单个元素.

$hash{key} is a single element within the hash.

因此,\%hash 是对 %hash 的引用,即整个哈希,在这种情况下,这似乎是您打算返回的内容.\$hash{key} 是对单个元素的引用.

Therefore, \%hash is a reference to %hash, i.e., the whole hash, which appears to be what you intend to return in this case. \$hash{key} is a reference to a single element.

你的第二个问题变得棘手的地方是引用总是标量,不管它们指的是什么.

Where it gets tricky in your second question is that references are always scalars, regardless of what they refer to.

$hash_ref = \%hash

要从您引用的散列中获取元素,您需要先取消引用它.这通常使用 -> 运算符完成,如下所示:

To get an element out of a hash that you have a reference to, you need to dereference it first. This is usually done with the -> operator, like so:

$hash_ref->{key}

请注意,当您从引用 ($hash_ref->{key}) 开始时,您使用 ->,但当您从实际散列开始时则不使用($hash{key}).

Note that you use -> when you start from a reference ($hash_ref->{key}), but not when you start from an actual hash ($hash{key}).

(作为问题 2 的旁注,不要在子调用前加上 & - 只需使用 authUser() 而不是 &authUser().& 在 Perl 5+ 中不再需要,它有你通常不想要的副作用,所以你不应该养成在任何地方使用它的习惯不需要.)

(As a side note on question 2, don't prefix sub calls with & - just use authUser() instead of &authUser(). The & is no longer needed in Perl 5+ and has side-effects that you usually don't want, so you shouldn't get in the habit of using it where it's not needed.)

对于问题 3,如果您只打算检查一次,您也可以循环遍历数组并检查每个元素:

For question 3, if you're only going to check once, you may as well just loop over the array and check each element:

my $valid;
for my $username (@list_of_users) {
  if ($login eq $username) {
    $valid = 1;
    last; # end the loop since we found what we're looking for
  }
}

if ($valid) {
  print "Found valid username $login\n";
} else {
  print "Invalid user! $login does not exist!\n";
}

这篇关于Perl:从子程序返回哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆