SPUG: The string name of a variable (or any identifier)

David Dyck david.dyck at fluke.com
Wed Jan 28 12:10:07 CST 2004


On Wed, 28 Jan 2004 at 01:46 -0800, Michael R. Wolf <MichaelRWolf at att.net>...:

> Anyone ever wanted to do something like this? I do it all the time in
> debugging, but I can't put it in a loop like this
>
> my ($x, $y, $z) = (1..3);
> @stuff_to_debug = ($x, $y, $z);
> foreach (@stuff_to_debug) {
>     printf "%s %d\n", $_.printable_name, $_;
> }
>
> To output this?
>
> $x 1
> $y 2
> $z 3

I was going to propose something based on B::Deparse
such as this tested code:

    use B::Deparse;
    my $deparse = B::Deparse->new("-p", "-sC");
    sub getnames($)
    {
	my $stuff_to_debug = shift;
	die "must pass code reff to getnames" unless ref $stuff_to_debug eq 'CODE';
	my $body = $deparse->coderef2text($stuff_to_debug);
	# remove sub wrappers
	$body =~ s/\s*//g;
	$body =~ s/^{\(//s;
	$body =~ s/\);}$//s;
	split /,/, $body;
    }

    my ($x, $y, $z) = (1..3);
    my $stuff_to_debug = sub {($x, $y, $z)};

    foreach (getnames $stuff_to_debug) {
	printf "%s %d\n", $_, eval $_;
    }

But then I thought if we wanted the names, why not pass them in
like this:-)

    my ($x, $y, $z) = (1..3);
    my @stuff_to_debug = qw($x $y $z);

    foreach (@stuff_to_debug) {
	printf "%s %d\n", $_, eval $_;
    }

Ps.
  Is anyone else getting hit by all the worm failed mail messages?



More information about the spug-list mailing list