Home > other >  Why can I not print text "$!"?
Why can I not print text "$!"?

Time:09-22

In Perl 5.26.2, when I run this code:

use POSIX qw(setlocale);
use locale;
setlocale LANGUAGE, "en_US";

print "$!";

I got an error:

No such file or directory

How can I print the two characters $!?

CodePudding user response:

There are a few issues here. And it's not clear which one you're misunderstanding.

$! is a variable. If you print a double-quoted string in Perl, it will expand any variables that are included in the string. If you don't want to treat $! as a variable, then you can either use a single-quoted string instead or escape the $ to remove its special meaning.

print '$!';
print "\$!";

$! is one of Perl's special built-in variables. If you look it up in perldoc perlvar, you'll see this:

$!

When referenced, $! retrieves the current value of the C errno integer variable. If $! is assigned a numerical value, that value is stored in errno. When referenced as a string, $! yields the system error string corresponding to errno.

So, when you print it, you are very likely to get what looks like an error - as it contains the last system error that your code generated. In this case, it's likely that your setlocale failed in some way and set the error variable.

CodePudding user response:

$! is a predefined variable in perl. And string that is built with double quotes will be interpolated.

Your code prints the error message produced by setlocale. To print literal "$!", you can use single quotes like print '$!';.

  •  Tags:  
  • perl
  • Related