in reply to Re^3: Odd number of elements in anonymous hash!
in thread Odd number of elements in anonymous hash!

I am trying to do is to add extra data in there "report_date". At the end I would like to have my file looked like this:
$VAR1 = [ { 'xml_api_reply' => { '-version' => '1', 'weather' => { 'report_date' => { '-d +ata' => '08-19-2012 @ 15:40:26' }, '-row' => '0', 'current_conditions' = +> { + 'icon' => { + '-data' => '/ig/images/weather/mostly_cloudy.gif' + }, + 'temp_f' => { + '-data' => '70' + }, + 'temp_c' => { + '-data' => '21' + }, + 'wind_condition' => { + '-data' => 'Wind: E at 7 mph' + }, + 'humidity' => { + '-data' => 'Humidity: 65%' + }, + 'condition' => { + '-data' => 'Mostly Cloudy' + } + }, } } }, ];

Thanks!

Replies are listed 'Best First'.
Re^5: Odd number of elements in anonymous hash!
by Athanasius (Archbishop) on Aug 20, 2012 at 09:08 UTC

    Hello Anonymous Monk,

    I don’t see how the code you gave in your original question can be what you are really using, since you have:

    ... open (FILE, ">data.txt") or die "can't open file: $!"; my $weather_data = do "data.txt"; ...

    which first opens the file for writing — thereby truncating it! — and only then reads in its (now empty) contents.

    In any case, it is simpler (and therefore less error-prone) to read and write the file in wholly separate steps. Here is a script which does that:

    #! perl use strict; use warnings; use Data::Dumper; use Date::Format; { my $file = 'data.txt'; my $today = get_timezone(); my $weather_data = do $file; ${ $weather_data->[0]{xml_api_reply}{weather} }{report_date} = { ' +-data' => $today }; open(my $out, '>', $file) or die "Cannot open file '$file' for wri +ting: $!"; print $out Dumper($weather_data); close($out) or die "Cannot close file '$file': $!"; } sub get_timezone { $ENV{'TZ'} = 'America/New_York'; return time2str('%m-%d-%Y @ %H:%M:%S', time); }

    This outputs:

    $VAR1 = [ { 'xml_api_reply' => { '-version' => '1', 'weather' => { 'report_date' => { '-d +ata' => '08-20-2012 @ 18:50:16' }, '-row' => '0', 'current_conditions' = +> { + 'icon' => { + '-data' => '/ig/images/weather/mostly_cloudy.gif' + }, + 'temp_f' => { + '-data' => '70' + }, + 'temp_c' => { + '-data' => '21' + }, + 'wind_condition' => { + '-data' => 'Wind: E at 7 mph' + }, + 'condition' => { + '-data' => 'Mostly Cloudy' + }, + 'humidity' => { + '-data' => 'Humidity: 65%' + } + } } } } ];

    as required.

    Hope that helps,

    Athanasius <°(((><contra mundum