<?xml version="1.0" encoding="windows-1252"?>
<node id="975589" title="Re: File handling? How to make the better one?" created="2012-06-11 11:08:24" updated="2012-06-11 11:08:24">
<type id="11">
note</type>
<author id="757127">
tobyink</author>
<data>
<field name="doctext">
&lt;blockquote&gt;&lt;code&gt;
if ( system("ls -l | grep datafile.json") == 0 ) {
&lt;/code&gt;&lt;/blockquote&gt;

&lt;p&gt;Sweet Jesus! Is this you trying to check whether a file exists?! You know Perl does have built-ins for checking the existence of a file...&lt;/p&gt;

&lt;code&gt;
if (-f "datafile.json") {
&lt;/code&gt;

&lt;p&gt;Using a few commodity modules from CPAN, you can make your life a lot easier...&lt;/p&gt;

&lt;code&gt;
#!/opt/lampp/bin/perl

use strict;

use CGI;
use CGI::Carp 'fatalsToBrowser';
use File::Slurp qw&lt; read_file write_file &gt;;
use JSON qw&lt; from_json to_json &gt;;

use constant USER_ACCOUNT_FILE =&gt; '/opt/lampp/htdocs/datafile.json';

sub store_user_account
{
	my ($name, $mail, $pass) = @_;

	my $existing_data = -f USER_ACCOUNT_FILE
		? from_json(scalar read_file(USER_ACCOUNT_FILE, err_mode =&gt; 'croak'))
		: [];
	
	push @$existing_data, {
		name  =&gt; $name,
		mail  =&gt; $mail,
		pass  =&gt; $pass,
	};
	
	write_file(
		USER_ACCOUNT_FILE,
		{ atomic =&gt; 1, err_mode =&gt; 'croak' },
		to_json($existing_data),
	);
}

sub process_cgi
{
	my ($q) = @_;
	
	store_user_account(
		map { scalar $q-&gt;param($_) } qw(name mail pass),
	);
	
	print $q-&gt;header('text/html');
	print "&lt;p&gt;Finished file.&lt;/p&gt;\n";
}

process_cgi( CGI-&gt;new );

&lt;/code&gt;

&lt;!-- Node text goes above. Div tags should contain sig only --&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-757127"&gt;
&lt;small&gt;&lt;small&gt;
&lt;tt&gt;perl -E'sub Monkey::do{say$_,for@_,do{($monkey=&amp;#x5B;caller(0)]-&gt;&amp;#x5B;3])=~s{::}{ }and$monkey}}"Monkey say"-&gt;Monkey::do'
&lt;/tt&gt;&lt;/small&gt;&lt;/small&gt;
&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
975568</field>
<field name="parent_node">
975568</field>
</data>
</node>
