在 Perl 的严格模式下使用动态生成的变量名 [英] Using a dynamically generated variable name in Perl's strict mode

查看:56
本文介绍了在 Perl 的严格模式下使用动态生成的变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想获取在动态生成的字符串中命名的变量的内容,但是在严格模式下实现此目的的所有努力都失败了.有几篇关于类似问题的帖子,但似乎没有一个对我有用.

Basically, I would like to grab the contents of a variable named in a dynamically generated string, but all efforts to accomplish this in strict mode have failed. There are several posts about similar problems, but none seem to have solutions that have worked for me.

这就是我想要做的:

# Fields:
$q1 = "ex. data 1";
$q2 = "ex. data 2";
$q3 = "ex. data 3";
$q4 = "ex. data 4";
$q5 = "ex. data 5";

# retrieve the desired field name.  q1, q2, q3, q4, or q5.
$field_name = fetch_the_desired_field_name();

# fetch the contents of the named field.  ex. data 1, ex. data 2, etc.
$contents_of_desired_field = $$field_name;

print $contents_of_desired_field;

有没有办法在严格模式下做到这一点?在关于类似问题的其他帖子中,人们说散列是答案,但我似乎不太明白如何用散列来做到这一点.不用说,这是一个非常简化的例子.在实际代码中,有 115 个可能的字段名称,都是从数据库中提取的,内容不可预测.

Is there a way to do this in strict mode? In other posts about similar problems, people say that hashes are the answer, but I can't seem to quite grasp how to do this with a hash. It goes without saying that this is a very simplified example. In the actual code, there are 115 possible field names, all pulled from a database, with unpredictable contents.

推荐答案

使用散列来做到这一点:

To do this with a hash:

商店:

$myHash{q3} = "ex. data 3";

检索:

$result = $myHash{q3};

这有多种好处,例如:

  • 满足使用严格";

  • Satisfies "use strict";

您可以通过 keys %myHash

由于字段名称是最后一点的列表,如果需要,您可以对它们进行任何其他列表操作(mapgrep)等...

Since the field names are a list as per the last point, you can do any other list operations on them if needed (map, grep) etc...

  • 例如,要仅获取字段名称为q[1-5]"形式的值,您可以执行以下操作:

  • For example, to get only the values where field name is of a form "q[1-5]", you can do:

@subset = @myHash{ grep m/q[1-5]/ keys %myHash }; # Use a slice @{} operator.

  • 大多数数据库 API(例如 DBI)都有调用,这些调用会在查询表中的行时自动返回这种精确格式的哈希(或者更确切地说是哈希引用)

  • Most database APIs (e.g. DBI) have calls which will automatically return back this exact format of a hash (or rather a hash reference instead) when querying a row from a table

    $hash_ref = $sth->fetchrow_hashref;
    

  • 这篇关于在 Perl 的严格模式下使用动态生成的变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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