mcudmore has asked for the wisdom of the Perl Monks concerning the following question:

I read in some values from a file containing 2 peices of data to create a hash. I am having trouble trying to create a dynamic reference to this hash based on scalars in the script. I suspect my interpolation is to blame. I have tried a variety of protections etc using \ and so on. Any help around? sample values file sapuser 1.2.3.4 sapuser 1.2.3.6 eof
#!d:\perl\bin\perl.exe sub initials { $ComDir='.\\'; $Inputfile='ProxyFTP'; $Outputfile='ftpreport.txt'; $Permsfile='userperms.txt'; } sub datacollect { open(PERF, "<$ComDir$Permsfile") || die ("died opening source +file $Permsfile") ; # Open the file @plines = <PERF>; chop (@plines); close(PERF); $pmax=scalar (@plines); } sub cleanupline { my($linein) =@_ ; $linein =~ s/[\n\r]//g, $linein; $linein =~ s/^[ \t]+//g,$linein; $linein =~ s/[ \t]+/ /g, $linein; } $ComDir='.\\'; &initials; &datacollect; open(NUREP, ">$Outputfile") || die ("died opening $Outputfile file") ; for($pindex=0; $pindex<$pmax; $pindex++) { # build permissions hash $plines[$pindex]=&cleanupline($plines[$pindex]); ($name,$value) = split/ /, $plines[$pindex],2; $name{$value}=1; } # next 3 lines should print Exists $nam='sapuser'; $val='1.2.3.4'; print "Exists\n" if exists $nam{$val}; # next 3 lines should not print Exists $nam='sapuser'; $val='1.2.3.7'; print "Exists\n" if exists $nam{$val}; close(NUREP);

Replies are listed 'Best First'.
Re: creating hash name from variables
by davorg (Chancellor) on Oct 09, 2002 at 15:10 UTC

    You're putting all your data into a hash called %name and then you're looking for it in a hash called %nam (without an 'e').

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      I was trying to create a set of hashes from the value file something like hash sapuser{1.2.3.4}=1 sapuser{1.2.3.6}=1 and so on.

        Ah. You were trying to create symbolic references. Don't do that.

        Why not use a hash of hashes instead?

        use strict; use warnings; my $ComDir='.\\'; my $Inputfile='ProxyFTP'; my $Outputfile='ftpreport.txt'; my $Permsfile='userperms.txt'; open(PERF, "<$ComDir$Permsfile") || die ("died opening source file $Permsfile: $!"); my %data; while (<PERF>) { chomp; my ($name, $val) = split / /, cleanupline($_), 2; $data{$name}{$val} = 1; } # next 3 lines should print Exists my $nam='sapuser'; my $val='1.2.3.4'; print "Exists\n" if exists $data{$nam}{$val}; # next 3 lines should not print Exists $nam='sapuser'; $val='1.2.3.7'; print "Exists\n" if exists $data{$nam}{$val}; sub cleanupline { local ($_) = @_; s/[\n\r]//g; s/^[ \t]+//g; s/[ \t]+/ /g; return $_; }
        --
        <http://www.dave.org.uk>

        "The first rule of Perl club is you do not talk about Perl club."
        -- Chip Salzenberg