-2

I have a simple foreach loop in Perl that logs into a few different remote hosts and runs a command which returns a numeric value. I want to save this value to a variable. The variable will be named after the individual hostnames (which are being looped through), like below:

host01_backup

host02_backup

etc...

Therefore my question - is it possible to do this within the loop.

foreach $i (@hosts) {
  print "hostname is: $i \n";
  ssh("ins\@$i", "$cmd"); # this is where I want to assign a variable which is part named using the contents of $i (hostname).

Cheers in advance!

jsjw
  • 147
  • 10

1 Answers1

2

Do not create dynamically named variables. They are far more trouble then they are worth. We have arrays and hashes which are designed for this.

use strict;
use warnings;
use v5.10;

my @hosts = get_hosts();
my %hostnames = (
    host01_backup => "some value",
    host02_backup => "some value",
)
foreach my $hostname (@hosts) {
    say "hostname is: $hostname";
    ssh($hostnames{"host" . $hostname . "_backup"}, $cmd);
}

I then want to save the output of the command that I run over the ssh connection in a variable that is named with the convention you've shown in the hash

This is the synopsis of Net::SSH::Perl:

use Net::SSH::Perl;
my $ssh = Net::SSH::Perl->new($host);
$ssh->login($user, $pass);
my($stdout, $stderr, $exit) = $ssh->cmd($cmd);

So you have the output from that in some variables.

You can store them in the hash (previously created with my %ssh_output) with:

$ssh_output{$hostname} = $stdout;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks for this. Apologies for being a novice with this - but could you explain the use of hashes here? & How is the variable being stored? – jsjw Dec 08 '17 at 11:54
  • Obligatory "symbolic references are a [bad idea](https://perl.plover.com/varvarname.html) link – Sobrique Dec 08 '17 at 11:54
  • .... actually the syntax on that `ssh` command looks a bit weird. SHould that be `$hostnames` rather than `%hostnames`? – Sobrique Dec 08 '17 at 11:56
  • 1
    [perldata](https://perldoc.perl.org/perldata.html) tells you about hashes and what they do. – Sobrique Dec 08 '17 at 11:56
  • @Sobrique — Yes, typo. Fixed. – Quentin Dec 08 '17 at 12:09
  • I still don't think this answers my question - I need to ssh using a value from the array. I then want to save the output of the command that I run over the ssh connection in a variable that is named with the convention you've shown in the hash. I'm just not seeing how the hash key host01_backup (for example) is being assigned the value of the output of the ssh command? – jsjw Dec 08 '17 at 12:27
  • @jsjw97 — You didn't mention that before, and there was no sign of anything being assigned in the question. I'll edit. – Quentin Dec 08 '17 at 12:35
  • Cheers for that - I put a small comment next to my snippets, but might have been hidden as you have to scroll to it.. I'll mark as solved. – jsjw Dec 08 '17 at 13:45