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


In reply to Re^5: Odd number of elements in anonymous hash! by Athanasius
in thread Odd number of elements in anonymous hash! by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.