Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Storing array or a hash into a text file 2

Status
Not open for further replies.

avashisht

Technical User
Feb 16, 2004
9
US
Hi,
I am veeeery new to perl..
i have a script where i am outputting the Environment variable to a HASH.
either i want to output hash values into a text file,
Or
get hash into an array and then print the array into the text file../
thanks
avashisht
 
Does the output from Data::Dumper's Dumper function suit you?

________________________________________
Andrew - Perl Monkey
 
you have to be very detailed andrew.. sorry abt that...
what ever it takes to get this out in the text file will be good,,
here is what i want to get into text file:
foreach $key (sort(keys %ENV)) {
print "$key = $ENV{$key}\n"
@array1 = keys(%ENV);
}

Thanks
Avashisht
 
Sorry, check search.cpan.org for the various serializer modules. The three popular ones are Data::Dumper [1], Storable [2], and FreezeThaw [3]. The first is most useful for a quick pretty-print of a data structure, but the others are much better for converting the serialized data back into real Perl structures again.

[1] [2] [3]
________________________________________
Andrew - Perl Monkey
 
How's this? No modules required.
Code:
#!perl
use strict;

open(ENVTMP, ">envtmp.txt") || die qq(Can't open "envtmp.txt" for output\n);

my $delim = "="; #use your favorite delimiter
my ($k, $v);

#Write key/value pairs from %ENV to file, joined by $delim
while (($k, $v) = each %ENV) {
    print ENVTMP join($delim, ($k, $v)), "\n";
}
close(ENVTMP) || die qq(Can't close output file "envtmp.txt"\n);

open(ENVTMP, &quot;<envtmp.txt&quot;) || die qq(Can't open &quot;envtmp.txt&quot; for input\n);
my %h;

#Read key/value pairs from file into hash.
while (<ENVTMP>) {
    chomp;
    ($k, $v) = split(/$delim/);
    $h{$k} = $v;
}
close(ENVTMP) || die qq(Can't close input file &quot;envtmp.txt&quot;\n);

#Print the hash.
for (sort keys %h) {
    print qq($_ => $h{$_}\n);
}
Example output (partial):

ALLUSERSPROFILE => C:\Documents and Settings\All Users
APPDATA => C:\Documents and Settings\mikevh\Application Data
CLASSPATH => &quot;C\QTJava.zip&quot;
CLIENTNAME => Console
COMMONPROGRAMFILES => C:\Program Files\Common Files
COMPUTERNAME => MIKE
COMSPEC => C:\WINDOWS\system32\cmd.exe
EMACSDATA => C:/emacs/emacs-20.7/etc
EMACSDOC => C:/emacs/emacs-20.7/etc
EMACSLOADPATH => C:/emacs/emacs-20.7/site-lisp;C:/emacs/emacs-20.7/lisp;C:/emacs/emacs-20.7/leim
EMACSLOCKDIR => C:/emacs/emacs-20.7/lock
EMACSPATH => C:/emacs/emacs-20.7/bin
EMACS_DIR => C:/emacs/emacs-20.7
EM_PARENT_PROCESS_ID => 2540
HOME => C:/
HOMEDRIVE => C:
HOMEPATH => \Documents and Settings\mikevh
LOGONSERVER => \\MIKE
NUMBER_OF_PROCESSORS => 1

 
If you're &quot;veeeery new&quot; to Perl you might want to ignore this, but I kept fooling around with the code I posted above, having fun with it (okay, so I have no life) and came up with the following more functional approach. (Same output.)
Code:
#!perl
# env2hash, more functional (and slightly OO) approach

use strict;
use warnings;
use Carp;
use FileHandle;

my $fh = FileHandle->new();

main: {
    my $delim = &quot;=&quot;; #use your favorite delimiter
    my $filename = &quot;envtemp.txt&quot;;
    hash2file($filename, $delim, \%ENV);
    my $h = file2hash($filename, $delim);
    printhash($h);
    exit(0);
}

sub hash2file {
    # Write key/value pairs from hash to file, joined by $delim
    my ($filename, $delim, $environ) = @_;
    $fh->open($filename, &quot;w&quot;) or 
        croak qq(Can't open &quot;$filename&quot; for output.\n);
    my ($k, $v);
    while (($k, $v) = each %$environ) {
        $fh->print(join($delim, ($k, $v)), &quot;\n&quot;);
    }
    $fh->close() or 
        croak qq(Can't close output file &quot;$filename&quot;.\n);
}

sub file2hash {
    # Read key/value pairs from file into hash.
    my ($filename, $delim) = @_;
    $fh->open($filename, &quot;r&quot;) or 
        croak qq(Can't open &quot;$filename&quot; for input\n);
    my %h;
    my ($k, $v);
    local $_;
    while ($_ = $fh->getline()) {
        chomp;
        ($k, $v) = split(/$delim/);
        $h{$k} = $v;
    }
    $fh->close() or 
        croak qq(Can't close input file &quot;$filename&quot;\n);
    \%h;
}

sub printhash {
    # Print the hash.
    my $h = shift;
    for (sort keys %$h) {
	print qq($_ => $h->{$_}\n);
    }
}
 
How abt this...
this serves my purpose, although the output file is not that cleanly formatted, but i had to run it once and i guess is pretty easy even for a newbie !!!!!

#!/usr/bin/perl

@array1 = (%ENV);
open (FILE, &quot;>/tmp/ashish.tmp&quot;) or die &quot;error opening file for writing: $!\n&quot;;
print FILE join(&quot;\n&quot;, @array1), &quot;\n&quot;;
close(FILE);


 
That gives you your keys on separate lines of the file from your values. The file ends up like

<key1>
<value1>
<key2>
<value2>
etc.

If that doesn't bother you, fine.
Are you ever going to want to read this back out into a hash? (Yes, it can be done ...)

If you're going to go that route, why bother with @array1?
Just say
Code:
print FILE join(&quot;\n&quot;, %ENV), &quot;\n&quot;;
 
That seems like an awful lot of work to me, especially considering that Data::Dumper (icrf gave the link) is installed as a standard Perl module.

Incidentally, Data::Dumper is extremely easy to turn back into a real structure. Just read in your output file and eval() it.
 
I think I will go with DataDumpr..
better that way...

Thanks all you guys... it was a great help
 
seems like i have a question that needs to be answered again,
I used the DataDumper mode:

use Data::Dumper;
$Data::Dumper;
print Dumper(%ENV);

now the output looks something like this:
$VAR5 = 'DBDIR';
$VAR6 = '/var/spool/Tivoli/tmrdev200.db';
$VAR7 = 'NO_J2D_DGA';
$VAR8 = 'true';
$VAR9 = 'HOME';
$VAR10 = '/home_dir/z016925';

the Variables and their values are in different lines..
1) how can i print that in line? If i need to as i will be using that in the script and the doing some cuts here and there to get the variable and value i need
2) how can i print that to a file ? do i need to use a File Handler?

will appreciate any response...
thanks

 
Pass a reference to the %ENV hash, instead of the hash itself.
Code:
print Dumper(\%ENV);

To print to a file
Code:
print OUTFILE Dumper(\%ENV);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top