in reply to Re: Proper use of split
in thread Proper use of split

So, the reason that the split approach fails is that it is very sensitive to changes in input structure. If we examine the corrected input stream, you'll note that it is now valid JSON, so the script
use strict; use warnings; use JSON; use Data::Dumper; $_ = '{"temp":75.50,"tmode":2,"fmode":0,"override":0,"hold":0,"t_cool" +:75.00,"tstate":0,"fstate":0,"time":{"day":4,"hour":13,"minute":49}," +t_type_post":0}'; print Dumper decode_json ($_);
outputs
$VAR1 = { 'fstate' => 0, 't_cool' => '75', 'time' => { 'hour' => 13, 'minute' => 49, 'day' => 4 }, 'fmode' => 0, 'tmode' => 2, 'temp' => '75.5', 'hold' => 0, 'override' => 0, 'tstate' => 0, 't_type_post' => 0 };

Rather than having to fight writing a parser, the module does the heavy lifting, and your script could be rewritten perhaps like:

use strict; use warnings; use JSON; open (my $fh, '<', '/home/julian/tstatcollect') or die "Open failed:$! +"; while (<$fh>) { chomp; my $obj = decode_json($_); print "Temperature: $obj->{temp}\n"; print "Tmode: $obj->{tmode}\n"; print "Fmode: $obj->{fmode}\n"; print "Override: $obj->{override}\n"; print "Hold: $obj->{hold}\n"; print "tcool: $obj->{t_cool}\n"; print "tstate: $obj->{tstate}\n"; print "fstate: $obj->{fstate}\n"; print "day: $obj->{time}{day}\n"; print "hour: $obj->{time}{hour}\n"; print "minute: $obj->{time}{minute}\n"; print "t_type_post $obj->{t_type_post}\n"; print "________\n"; }
which outputs
Temperature: 75.5 Tmode: 2 Fmode: 0 Override: 0 Hold: 0 tcool: 75 tstate: 0 fstate: 0 day: 4 hour: 13 minute: 49 t_type_post 0 ________

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^3: Proper use of split
by Kenosis (Priest) on Jun 01, 2012 at 19:57 UTC

    This is excellent, kennethk!