Search code examples
perl

what does $^S mean in perl?


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|'

Solution

  • 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.