Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl associative arrays and variable assignment

I'm having trouble understanding how this is supposed to work. I have defined my two hashes outside of the while loop. And the goal is to be able to detect the shell type, and assign the appropriate hash to a new $shell variable. Here is the code I'm current trying..

#!/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);

I've tried many different things with no avail so I'm finally resorting to the pros here at stackoverflow to get some direction!

Any help is very much appreciated. Thank you.

like image 849
Brandon Avatar asked Dec 28 '25 15:12

Brandon


2 Answers

Your my $shell is lexical inside of the if block. Move it outside the if or it is not available there. Adding some indentation helps to spot that.

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

After that, you will get a warning saying %shell is undefined. That's because you are using $shell{url} but you defined $shell as a hash ref, so you need $shell->{url} or $$shell{url} in your print.

like image 184
simbabque Avatar answered Dec 31 '25 07:12

simbabque


Two issues:

  1. Your my $shell variable is lexically scoped to the if statement. It won't be visible outside.

  2. The $shell variable is a hashref. So you have to access elements using $shell->{url}. Note the arrow.

So the following should work:

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

print "Shelltype: $shelltype\n";
print "Should be $shell->{url}\n";
like image 30
nwellnhof Avatar answered Dec 31 '25 05:12

nwellnhof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!