arrays - Perl 关联数组和变量赋值

标签 arrays perl associative-array

我无法理解这应该如何工作。我在 while 循环之外定义了我的两个散列。目标是能够检测 shell 类型,并将适当的哈希分配给新的 $shell 变量。这是我目前正在尝试的代码..

#!/usr/bin/perl
use strict;
use warnings;

use POSIX;
use DateTime;
use Term::ANSIColor qw(:constants);

local $Term::ANSIColor::AUTORESET = 1;
my $dt = DateTime->now;   # Stores current date and time as datetime object

my %multicity = (
        url        => "example.com",
        ftpuser    => "user",
        ftppass    => "pass",
        remote_dir => "/httpdocs/",
        dbname     => "database"
);

my %singlecity = (
        url        => "example2.com",
        ftpuser    => "user",
        ftppass    => "pass",
        remote_dir => "/httpdocs/",
        dbname     => "database"
);

open (MYFILE, 'sites.txt');

LINE: while (<MYFILE>) {
    next LINE if /^#/;
    my ($shelltype, $siteurl, $ftpuser, $ftppass, $dbname) = split /\|/;

    # 1|example.com|user|pass|databasename - This should be a singlecity shell type.
    if ($shelltype == 1) { my $shell = \%multicity; } else { my $shell = \%singlecity; };

    print "Shelltype: $shelltype\n";
    print "Should be $shell{url}\n";

}
close (MYFILE);

我尝试了许多不同的方法,但无济于事,所以我终于求助于 stackoverflow 的专业人士来获得一些方向!

非常感谢任何帮助。谢谢。

最佳答案

你的 my $shellif block 内的词法。将它移到 if 之外,否则它在那里不可用。添加一些缩进有助于发现这一点。

my $shell;
if ($shelltype == 1) { 
  $shell = \%multicity; 
} else { 
  $shell = \%singlecity; 
};

之后,您将收到一条警告,提示 %shell 未定义。那是因为您使用的是 $shell{url} 但您将 $shell 定义为哈希引用,因此您需要 $shell->{url}$$shell{url} 在您的 print 中。

关于arrays - Perl 关联数组和变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21245350/

相关文章:

ios - 在 TableView 中显示 plist 中的数据数组

perl - perl 中的简单并行处理

使用命名占位符时 PHP/SQL 插入错误

php - 从关联数组中提取值的子集 (php)

linux - Bash 脚本 - 遍历关联数组列表的 "variable"变量名

创建均匀分布的 double 值数组

C语言如何修复我的调用函数

java - 返回点击按钮的索引?

Perl - 递归检查目录树

mysql,如何创建表并自动跟踪添加或删除行/表的用户