Home > Back-end >  what does $^S mean in perl?
what does $^S mean in perl?

Time:12-15

What does $^S mean in perl? looking at https://perldoc.perl.org/perlvar all I can find is

Having to even think about the $^S variable in your exception handlers is simply wrong.

perl -e 'print qq|What does "\$^S":$^S mean in perl?\n Thank you\n|'

CodePudding user response:

perlvar actually says the following for $^S:

Current state of the interpreter.

$^S         State
---------   -------------------------------------
undef       Parsing module, eval, or main program
true (1)    Executing an eval or try block
false (0)   Otherwise

The first state may happen in $SIG{__DIE__} and $SIG{__WARN__} handlers.

Say you want to decorate exceptions with a timestamp, but only those that aren't caught to avoid breaking anything or having multiple timestamps added.

$ perl -e'
   use POSIX qw( strftime );

   # Decorate error messages, part 1.
   local $SIG{ __DIE__ } = sub {
      # Avoid exiting prematurely.
      return if $^S;

      my $ts = strftime( "%FT%TZ", gmtime() );
      print( STDERR "[$ts] $_[0]" );
      exit( $! || $? >> 8 || 255 );
   };

   # Decorate error messages, part 2.
   local $SIG{ __WARN__ } = sub {
      # Avoid mangling exceptions that are being handled.
      return if $^S;

      my $ts = strftime( "%FT%TZ", gmtime() );
      print( STDERR "[$ts] $_[0]" );
   };

   eval {
      die( "Some caught exception\n" );
   };
   if ( $@ ) {
      warn( "Caught: $@" );
   }

   die( "Some uncaught exception\n" );
'
[2022-12-15T05:57:44Z] Caught: Some caught exception
[2022-12-15T05:57:44Z] Some uncaught exception

Without checking $^S, we would have exited prematurely.

CodePudding user response:

It's a bit further down on perlvar.

Current state of the interpreter.

$^S         State
---------   -------------------------------------
undef       Parsing module, eval, or main program
true (1)    Executing an eval or try block
false (0)   Otherwise

Confusingly, the variable's full use English name is $EXCEPTIONS_BEING_CAUGHT, despite, as the documentation goes on to admit, the fact that the variable really doesn't inform you as to whether or not an exception is being caught.

  •  Tags:  
  • perl
  • Related