Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

How to copy an array to a hash?

by Ethen (Acolyte)
on Jan 11, 2008 at 06:17 UTC ( #661812=perlquestion: print w/replies, xml ) Need Help??

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

Hi, I want to read a file and copy the data into an array. The file whose contents needs to be copied is below:
#File name: auto.txt #! usr/bin/perl -w $Srvr_mngr = `C:\Siebel\WebClient\Bin\srvrmgr.exe`; $Server_name = "server"; $User_name = "user"; $Password = "password"; $List_of_Values = `C:\Siebel\WebClient\Bin\ListOfValues.ifb`; $Row_id = "Session id";
Now see the code below that stored the file content into an array and further to Hash(Associative array.)
#! /usr/bin/perl if(open(INFILE,"auto.txt")){ #Add the file contents to an array @data = <INFILE>; %edit = @data } else { print "No such file or directory\n"; }
Now I have the contents of the "auto.txt" in associative array "%edit". I want to assign keys to the elements of the file copied. Do I need to define the hash and assign each key to the variables. e.g
%edit = (e101 => 'Srvr_mngr ', e102 => 'Server_name', e103 => 'User_na +me ', e104 => 'Password').......;
or is there any other way to assign keys to the elements of the file "auto.txt". Please assist Cheers!! Ethen ---------------------- Hi, Thanks for the assitance, I have tried to do now this way. PFB first the contents of file "para.txt".
#para.txt #this file contains the paramters to be used in the #command line. SRVMNGR = "E:\siebel\siebsrvr\bin\srvrmgr " GATEWAY = "gateway server name" ENTERPRISE SERVER = "enterprise server name" SERVER = "server name" USER = "user" PASSWORD = "password" SYSTEM_NAME = "WfProcMgr"
Now I need to invoke a command line from my script. I have tried something like this.
#File name: "migrate.pl" #This file will fetch the data from "para.txt" and use #them to invoke + the command line open(INFD, "para.txt") or die "Error reading the file.....Please try a +gain\n"; @str = <INFD>; $i=0; $edit = {}; while($i <= $#str) { $line = $str[$i]; chop($line); @lineContents = split(/=/, $line); $edit->{$lineContents[0]} = $lineContents[1]; # print "one = $lineContents[0], two = $lineContents[1]\n"; $i++; } foreach $i (keys (%$edit)) { print "Key = $i Val = $edit->{$i}\n"; } @str1 = `SRVMNGR – g GATEWAY –e ENTERPRISE SERVER –s USER –p PASSWORD +–c”Run Task for comp SYSTEM_NAME processName="UDA Batch Deployment", +RowId=”Captured Session Id”`; print @str1; #I doubt if this will invoke the command line
Now, it is required that when this command line is invoked in “migrate.pl”, lets say e.g SRVMNGR should automatically fetch its value from “para.txt” file which is "E:\siebel\siebsrvr\bin\srvrmgr". Same case with other parameters in the command line. How shall I invoke the command line in the script? Please suggest a clear alternative. Also, Once I got the contents of para.txt in "key" and "value", will the command line automatically picks up the values from them? Sorry for the long query but i would be greatful if someone provides me a solution. Let me knw if further details are required. Cheers!! Ethen

Replies are listed 'Best First'.
Re: How to copy an array to a hash?
by CountZero (Bishop) on Jan 11, 2008 at 06:49 UTC
    You are there, ... almost.

    All you have to do is split each element from your array into a key and value part.

    One possible solution is:

    %edit = map {split /\s+=\s+/} @data;

    It doesn't make a hash like you wish (with the strange "e101" keys) but that did not make any sense to me, so I went for a more logical solution: the keys are your variable names and the values are the contents of the variables.

    But you are re-inventing wheels by making one more configuration handler. Have a look at (for instance) YAML or Config::Auto or Config::Any.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      This may be useful:

      my $data = do { local $/ = undef; <INFILE> }; my %edit = split /=|\r\n/, $data;

      Hashes are almost like arrays with odd element number. Since split is splitting on new lines and = signs, and you appear to have it this way, it will construct the hash for you.

      Hope this helps.

      Igor 'izut' Sutton
      your code, your rules.

        Good idea! But why use \r\n instead of \n?

        Also it looks like the OP's input file might have empty lines and that could throw the sequence out of sync unless you take special care (perhaps by using \n+ ?).

        CountZero

        A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: How to copy an array to a hash?
by parv (Vicar) on Jan 11, 2008 at 06:33 UTC

    Seems like a query similar to How [to] include a file in Perl script by OP, resulting quite possibly in the same responses.

    Forgot to mention earlier ... There can be more reasons for failure to open a file other than a non-existing file: permission errors, running out of file descriptors, and possibly others (that I do not know about). Therefore, instead of ...

    my $file = 'file-name'; if( open(HANDLE, $file) ) { ... } else { print "No such file or directory\n"; }

    ... should use $! (aka $OS_ERROR, $ERRNO) in printing of a message ...

    if ( open my $handle, '<', $file ) { ... } else { print $!, "\n"; #warn "Cannot open file '$file' to read: $!"; }

    ... so that you can have as close to the real reason for open failure as possible.

Re: How to copy an array to a hash?
by MaW (Initiate) on Jan 11, 2008 at 09:26 UTC
    I'm not sure what you're really trying to achieve with this, but let's make sure you know how arrays get assigned to hashes.
    my @array = (1, 2, 3, 4, 5, 6); my %hash = @array;
    Is the same as saying:
    my %hash = ( 1 => 2, 3 => 4, 5 => 6 );
    apart from not having an @array floating around in the second version of course. If you really want to get each non-empty line in your input file into a hash with a key that's generated by some iterative process, you want something like
    open my $file, '<', $filename or die "Unable to open '$filename': $!"; my %edit; for (<$file>) { next if //; chomp; # Some code to get a $key with an appropriate value $edit{$key} = $_; } close $file;
Re: How to copy an array to a hash?
by olus (Curate) on Jan 11, 2008 at 12:31 UTC
    Hi Ethen,
    below is an example of how you can parse the information on your file.
    Note that you can use your file descriptor (INFD) where I have <DATA> to read the info from the file.
    To execute svrmngr use the system function instead of the final print.
    use strict; use warnings; my @data = <DATA>; my %conf = (); map{ $_ =~ /(\w*)\s*=[^\w]*(.*)('|")/; $conf{$1} = $2; } grep /=/, @da +ta; #use Data::Dumper; #print Dumper(\%conf); # to see what we got print ("srvmngr -g $conf{'GATEWAY'} -s $conf{'USER'} -....."); __DATA__ #para.txt #this file contains the paramters to be used in the #command line. SRVMNGR = "E:\siebel\siebsrvr\bin\srvrmgr " GATEWAY = "gateway server name" ENTERPRISE SERVER = "enterprise server name" SERVER = "server name" USER = "user" PASSWORD = "password" SYSTEM_NAME = "WfProcMgr"
    This outputs
    srvmngr -g gateway server name -s user -.....
    If you must have the ' or " for the values on the right side, then change the regexp to
    map{ $_ =~ /(\w*)\s*=\s*(.*)\n/; $conf{$1} = $2; } grep /=/, @data;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://661812]
Approved by McDarren
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2021-04-16 09:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?