Retrieve value from a form and write to a file

2019-09-19 17:44发布

i have a form named

index.cgi

and a configuration file named

video.start

After the user select from the drop down menu and press submit, the value will be read and write into the configuration file. Here is a snippet from my form:

<tr><td>
<form method="POST" action="index.cgi">
<table>
<tr><th colspan="2">Video</th></tr>
<tr><td align="right"><b>Video Source :</b></td><td align="left">
<select name="channel1" size="1">
<option value="/dev/video0">/dev/video0</option>
<option value="/dev/video1">/dev/video1</option>
<option value="/dev/video2">/dev/video2</option>
<option value="/dev/video3">/dev/video3</option>
</select>
</td></tr>
</table>
</td></tr>
<tr>
<td colspan="2">
<div id="button">
<input type="submit" value="Submit"><input type="reset" value="Clear">
</div>
</form>
</td>
</tr>

and here is the code from index.cgi:

my $file = "video.start";

open (my $in, "+<", $file);
open (my $out, "+<", $file);

my $a = CGI->new();
$video = $a->param('channel1');

while(<$in>)
{
    print $out $_;
    last if $.==3;
}

while(my $data = <$in>)   
{
    #logic

    print $out $data;
    last if $.==5;
}

Finally, here is what my configuration file looks like:

#Only change at [udp://#] segment 
#This config file is for video

ffmpeg -f video4linux2 -i /dev/video0 -vcodec libx264 -preset ultrafast -tune zerolatency -s qvga -r 30 -qscale 5 -an -flags low_delay -bsf:v h264_mp4toannexb -maxrate 750k -bufsize 3000k -rtbufsize 300k -f h264 udp://# 

If you can see from the configuration form, after the user submitted the value, the /dev/video0 will change in the configuration file according to the value submitted by the user. But how can i achieve this in my logic?

标签: html forms perl
1条回答
成全新的幸福
2楼-- · 2019-09-19 17:48

The biggest trick to this is that you need to flock your files before editing them so there isn't a race condition.

use strict;
use warnings;
use autodie;

use Fcntl qw(:flock);

open my $fh, '<+', 'foobar.txt';
flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n";

After that, just read How do I change, delete, or insert a line in a file, or append to the beginning of a file?. I personally would go with Tie::File as I think that's probably the easiest way to edit a file in this context.

查看更多
登录 后发表回答