Using a dynamically generated variable name in Perl's strict mode [duplicate]

99封情书 提交于 2019-12-01 17:52:53

To do this with a hash:

Store:

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

Retrieve:

$result = $myHash{q3};

This has multiple benefits such as:

  • Satisfies "use strict";

  • You can loop over all the field names via keys %myHash

  • 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...

    • 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.
      
    • 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;
      

You don't want to dynamically generate variable names! Instead, use a hash or an array:

my @q = ("ex. data 1", ..., "ex. data 5");

my $contents  = $q[ $some_index ];

print $contents;

Where $some_index is set to the desired index, thus removing any need for dynamic names.

strict explicitly does not allow you to use what are called "symbolic references". You can get around this by asking Perl for permission:

use strict;
use warnings;
use 5.10.0;

our $x = '5';
my $field_name = 'x';

my $contents;
{ # no strict is lexially scoped
    no strict 'refs';
    $contents = ${$field_name};
}

say $contents;

Note that the referenced variable has to be dynamic, not lexical, and that this practice is generally discouraged. Here's how you solve your problem with hashes, the correct data type:

# Fields:
my %data = (
    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 = $data{$field_name};

print $contents_of_desired_field;

There. No messy no strict, just one variable holding all your data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!