Sie haben es wahrscheinlich schon funktioniert, aber fügen Sie noch einen kleinen Kommentar, in Bezug auf die Frage, wie Sie den Hash von einer Funktion zurückgeben.
Hier ist ein Beispiel:.
Eingang -datei (die folgende verwendet, die, wie ich glaube, eine ähnliche Struktur wie die Eingabe -Dateien enthält
===|showcommand|
cmd1
cmd2
cmd3
cmd4
===|testcommand|
command1
command2
command3
===|anothercommand|
another1
another2
another3
another4
Perl -script:
use strict;
# Calling ReadCommandFile to build hash.
my %commands = ReadCommandFile("./commands.txt");
# ReadCommandFile - reads commands.txt and builds
# a hash.
sub ReadCommandFile()
{
my $file = shift;
my %hash =();
my $name;
open(FILE, "<$file");
while(<FILE>)
{
if($_ =~ /===\|(.*)\|/)
{
$name = $1;
$hash{$name} = [];
}
else
{
my $line = $_;
$line =~ s/\n$//;
push(@{$hash{$name}}, $line);
}
}
close(FILE);
return %hash;
}
Als Ergebnis sollten Sie den folgenden Hash erhalten (Ausgabe von Data :: Dumper):
$VAR1 = 'anothercommand';
$VAR2 = [
'another1',
'another2',
'another3',
'another4'
];
$VAR3 = 'showcommand';
$VAR4 = [
'cmd1',
'cmd2',
'cmd3',
'cmd4'
];
$VAR5 = 'testcommand';
$VAR6 = [
'command1',
'command2',
'command3'
];
Sie können dann diese einzelnen Elemente wie Zugang:
den dritten Befehl von "Showcommand" Get:
print "\nCommand #3: " . $commands{'showcommand'}[2];
Ausgang: cmd3
Die Daten aus der Datei wird in einen Hash kopiert und die Befehle werden als Array unter den jeweiligen Schlüsselwörtern hinzugefügt.
Danke!
Bitte lesen Sie [ask], und bearbeiten Sie dann diese Frage, um eine [mcve] einzuschließen. –