System calls fail. In C, you check the global errno variable (or GetLastError() on Windows). In Affix, we expose this via errno().
The Recipe
We will try to open a file that doesn't exist.
use v5.40;
use Affix qw[:all];
# fopen returns NULL on failure
affix libc, 'fopen', [ String, String ] => Pointer [Void];
my $file = fopen( 'non_existent_file.txt', 'r' );
if ( is_null($file) ) {
# get_system_error returns the numeric error code
# In numerical context: errno
# In string context: strerror(errno)
my $err = Affix::errno();
die sprintf 'Could not open file: %s (%d)', $err, $err;
}
Kitchen Reminders
-
errnoreturns a dualvar- Numeric:
2(ENOENT) - Stringified: "No such file or directory"
This makes logging errors rather convenient.
- Numeric: