in reply to Working with arrays of variables
Here's another couple of things to add to the tips you have already received:
Your "desired" variables.txt output could and should omit the leading '$' from the variable names. There's no reason to have it in there, and you'll have to strip it after you read the file if you want to work easily with the contents. I suggest that your output file should be of the format:
cheese=cabrales tomato=orlando mass=secret
etc.
Since your file is in the format of an *.ini file, you should look into the Config::Tiny module (available on CPAN) which simplifies reading from and writing to *.ini-style files.
use strict; use warnings; use Config::Tiny; my $ini = Config::Tiny->new; my $outfile = 'pizza.ini'; my %data = ( 'cheese' => 'cabrales', 'tomato' => 'orlando', 'mass' => 'secret', 'USERNAME' => $ENV{'USERNAME'}, ); $ini->{'MySectionName'} = {}; # new section while( my ($key, $val) = each %data ) { $ini->{'MySectionName'}->{ $key } = $val; } $ini->write($outfile, 'utf8');
This outputs a file containing the following:
[MySectionName] USERNAME= cheese=cabrales mass=secret tomato=orlando
Note that the value for USERNAME is blank, because $ENV{'USERNAME'} does not exist on all platforms, e.g. on my Mac laptop. You should make this cross-platform.
Note that the data are contained in a hash; as others have said, you should convert your data to a hash or hashes before you do anything else. Post a followup question here if you need help with that.
Also: learn to use Data::Dumper whenever you are developing code with, um, data.
use strict; use warnings; use feature qw/ say /; use Data::Dumper; my %data = ( 'foo' => 'bar', $cheese => 'cabrales', 'USERNAME' => $ENV{'USERNAME'} ); say Dumper( %data );
If you run this, you will get an error because $cheese is not pre-declared. That's why you must use strict!!!
use strict; use warnings; use feature qw/ say /; use Data::Dumper; my %data = ( 'foo' => 'bar', '$cheese' => 'cabrales', 'USERNAME' => $ENV{'USERNAME'} ); say Dumper( \%data );
If you run this, you will see if the value of $data{'USERNAME'} is undefined ... before you pass it on.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Working with arrays of variables
by perl_noobs (Initiate) on Jun 23, 2015 at 08:20 UTC | |
by 1nickt (Canon) on Jun 23, 2015 at 10:28 UTC |