Assertions: Difference between revisions

→‎{{header|Perl}}: rearrangements
(→‎{{header|PARI/GP}}: more traditional PARI)
(→‎{{header|Perl}}: rearrangements)
Line 662:
 
=={{header|Perl}}==
While not exactly an assertion, a common Perl idiom is to use <code>... or die ...</code> to throw an exception when a certain statement is false.
 
<lang perl>open my $fh, '<', 'file' or die "Cannot open file: $!\n"; # $! contains the error message from the last error</lang>
<lang perl>myprint "Give me $a =number: 5";
Note: the above "or die" idiom is not needed when the "autodie" pragma is in use:
chomp(my $a = <>);
<lang perl>use autodie;
open my $fh, '<', 'file'; # automatically throws an exception on failure</lang>
 
Another example:
<lang perl>my $a = 5;
#...input or change $a here
$a == 42 or die "Error message\n";
 
# or, alternatively:
# Alternatives
die "Error message\n" unless $a == 42;
# or:
die "Error message\n" if not $a == 42;
# or just:
die "Error message\n" if $a != 42;</lang>
 
This idiom is typically used during file operations:
<lang perl>open my $fh, '<', 'file'
<lang perl>open my $fh, '<', 'file' or die "Cannot open file: $!\n"; # $! contains the error message from the last error</lang>
Note: the above "or die" idiomIt is not needed whenwhith the "autodie" pragma is in use:
<lang perl>use autodie;
open my $fh, '<', 'file'; # automatically throws an exception on failure</lang>
 
Some third-party modules provide other ways of using assertions in Perl:
1,934

edits