Skip to content

Instantly share code, notes, and snippets.

@cxw42
Last active June 22, 2019 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cxw42/b347b7067b3744017662eaad1b9d04c6 to your computer and use it in GitHub Desktop.
Save cxw42/b347b7067b3744017662eaad1b9d04c6 to your computer and use it in GitHub Desktop.
Investigating ${^WARNING_BITS} in Perl 5.26.2
use 5.014;
use warnings;
use lib '.';
use W;
say "running";
no warnings;
W->report; # 0000...
use warnings;
W->report; # 1010...
package W;
#use Data::Dumper;
use strict;
use 5.014;
sub import {
say "Compile time: ", unpack('b*', ${^WARNING_BITS});
# ${^WARNING_BITS} is only available at compile time per
# https://www.perlmonks.org/?node_id=611472
}
sub report {
#my(@callers_bitmask) = (caller(0))[9]; # What warnings.pm does
my @caller0 = caller(0); # Who called us
# Must be caller(0), not just caller(), because without a parameter
# caller only returns the package, filename, and line number.
my $callers_bitmask = $caller0[9];
#say Dumper(\$callers_bitmask);
say "Runtime at $caller0[1]:$caller0[2]: ", unpack('b*', $callers_bitmask);
# E.g., "Runtime at main.pl:9: ..."
}
1;
@cxw42
Copy link
Author

cxw42 commented Jun 22, 2019

${^WARNING_BITS} is only available at compile time per https://www.perlmonks.org/?node_id=611472 . This matches my experience. As far as I can tell, the Perl source makes ${^WARNING_BITS} magical. Then, when the warnings pragma changes ${^WARNING_BITS} at compile time, PL_compiling.cop_warnings is updated. Somehow, PL_compiling.cop_warnings must be getting stashed away where caller() can access it at runtime.

Example output

perl main.pl produces:

Compile time: 1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010
running
Runtime at main.pl:9: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

(this is after no warnings)

Runtime at main.pl:12: 1010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010

(this is after use warnings)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment