Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sysopen example doesn't work

Tags:

perl

I got this perl example that's suppose to demonstrate sysopen and printf, except so far it only demonstrates die.

#! /usr/bin/perl  
$filepath = 'myhtml.html';
sysopen (HTML, $filepath, O_RDWR|O_EXCL|O_CREAT, 0755) 
    or die "$filepath cannot be opened.";
printf HTML "<html>\n";

but when I execute the code it just dies.

myhtml.html cannot be opened. at file_handle.pl line 7.

myhtml.html does not exist, but it should have been created by the O_CREAT flag. shouldn't it?


EDIT

I have edited the code to include the suggestions about use strict and $!. Below is the new code and its result.

#! /usr/bin/perl
use strict; 
$filepath = "myhtml.html";

sysopen (HTML, '$filepath', O_RDWR|O_EXCL|O_CREAT, 0755) 
    or die "$filepath cannot be opened. $!";
printf HTML "<html>\n"; 

output, due to the use strict, gave us a whole bunch of errors:

Global symbol "$filepath" requires explicit package name at file_handle.pl line 3.
Global symbol "$filepath" requires explicit package name at file_handle.pl line 5.
Bareword "O_RDWR" not allowed while "strict subs" in use at file_handle.pl line 5.
Bareword "O_EXCL" not allowed while "strict subs" in use at file_handle.pl line 5.
Bareword "O_CREAT" not allowed while "strict subs" in use at file_handle.pl line 5.
Execution of file_handle.pl aborted due to compilation errors.

EDIT 2

Based on everyone's suggestion and help, here is the final working code:

#! /usr/bin/perl
use strict;
use Fcntl;

my $filepath = "myhtml.html";

sysopen (HTML, $filepath, O_RDWR|O_EXCL|O_CREAT, 0755) 
    or die "$filepath cannot be opened. $!";
printf HTML "<html>\n"; 
....
like image 543
D.Zou Avatar asked Nov 30 '22 05:11

D.Zou


1 Answers

O_RWDR, O_EXCL, and O_CREAT are all constants defined in the Fcntl module. Put the line

use Fcntl;

near the top of your script.

like image 120
mob Avatar answered Dec 06 '22 09:12

mob