LanX has asked for the wisdom of the Perl Monks concerning the following question:

Hi

Are there any introspection mechanisms for perl labels?

For instance is it possible to get the line number of a label?

Cheers Rolf

PS: to be more precise: I don't include "code filter" in "any mechanism" and would rather prefer a CORE solution...

To be more explicit: I'm rather thinking of using something like investigation a package stash or (more likely) using something like PadWalker (since labels are scoped) - the common ways to introspect variables.

UPDATE: I'm not sure if I should better ask for "reflection" instead of "introspection" ... reading WP I couldn't find out if these concepts are really different or just synonyms(!?!).

Replies are listed 'Best First'.
Re: Introspection of labels possible?
by ig (Vicar) on Aug 30, 2009 at 22:15 UTC

    You might consider B. Perhaps something like:

    #!/usr/local/bin/perl use strict; use warnings; use B; HERE: B::walkoptree(B::main_root(), "print_label"); THERE: exit(0); sub B::OP::print_label { my $op = shift; if(ref($op) eq 'B::COP') { my $label = $op->label; if(defined($label)) { my $file = $op->file; my $line = $op->line; print "$label: $file: $line\n"; } } }

    Which produces

    HERE: ./test.pl: 6 THERE: ./test.pl: 8

    update: The label, line and file information is stored in the Code tree (a.k.a. OP tree) - not in any stash or pad.

      Wow, nice!!!

      Escpecially thank you for showing me new ways for how to analyze the op-tree! 8)

      Cheers Rolf

Re: Introspection of labels possible?
by shmem (Chancellor) on Aug 30, 2009 at 19:12 UTC
    For instance is it possible to get the line number of a label?

    If you remember them, yes ;-)

    #!/usr/bin/perl use strict; use warnings; my $i; my $FOO_LABEL_LINE = __LINE__; FOO: { $i++; redo FOO if $i < 10; } print "Label FOO is at line $FOO_LABEL_LINE\n"; __END__ Label FOO is at line 8
    but I'm afraid this isn't what you want...