Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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";

This line:

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

should be:

print "Should be $shell->{url}\n";

The reason is that you are assigning a reference to one of your two hashes to $shell, so to access a value in it you need to de-reference (using the -> operator).

In addition, as pointed out by nwellholf, the $shell variable is local to the if statement so you would get a compilation error there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top