简体   繁体   English

如何在perl中使用查找文本作为变量?

[英]how to use find text as variable in perl?

I have variables in file1.pm file file1.pm 我在file1.pm文件file1.pm中有变量

package oa;
use strict;
use warnings;
our $first1= 'DTH';
1;

Now want access this variable within variable, this is my main program but I did't get output i know problem is "oa:$var" Can i use “/oa::$var/ “ like this to access variable? 现在想访问变量中的这个变量,这是我的主程序,但是我没有得到输出,我知道问题是“ oa:$ var”我可以使用“ / oa :: $ var /”来访问变量吗?

#!/usr/bin/perl
use file1;
$input='DTH';
$var=first . 1;
if($input =~ /oa::$var/){
print “DTH”;
}

Perl is not PHP, and the $ sigil comes in front of the package name: If you want to access a package variable, then do $PackageName::var_name . Perl不是PHP,并且$标记在软件包名称的前面:如果要访问软件包变量,请执行$PackageName::var_name

./MyPackage.pm : ./MyPackage.pm

package MyPackage;  # package names should be CamelCase!
use strict;
use warnings;

our $first1 = 'DHT';
1;

./script.pl : ./script.pl

use strict;
use warnings;
use MyPackage;

my $input = 'DHT';
if ($input =~ /$MyPackage::first1/) {
    print "DHT\n";
}

However, you are also refering to a variable by name. 但是,您还通过名称引用变量。 This is a bad thing to do, and makes it almost impossible to understand and maintain such a program. 这是一件坏事,并且几乎不可能理解和维护这样的程序。 You can use hashes instead (also known as associative arrays, maps, or dictionaries): 您可以改用哈希 (也称为关联数组,地图或字典):

In MyPackage : MyPackage

our %stuff = (
    first1 => 'DHT',
    other1 => 'foobar',
);

In the script: 在脚本中:

my $var = 'first1';
if ($input =~ /$MyPackage::stuff{$var}/) {
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM