Re: getting {string} from \${string}
From: Anno Siegel (anno4000_at_lublin.zrz.tu-berlin.de)
Date: 01/29/05
- Next message: Anno Siegel: "Re: getting {string} from \${string}"
- Previous message: Gunnar Hjalmarsson: "Re: Search Through List"
- In reply to: bongo_at_frii.com: "getting {string} from \${string}"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 29 Jan 2005 01:54:03 GMT
<bongo@frii.com> wrote in comp.lang.perl.misc:
> Hi folks. Perl newbie here. Having a heck of a
> time with something which probably isn't that hard...
>
> When debugging code in progress, I often find myself
> typing:
>
> print "\$var1=$var1, \$var2=$var2 \n";
>
> not a big deal, but when you do it all the time, it
> would be nice to save some typing by putting it in a
> subroutine, such as:
>
> dbg_pr($var1,$var2);
>
> Easy enough if I just wanted the values, but I want to
> print both the variable names and the values, and I'd
> like to get both from one string. If I pass $var1 or \$var1
> I can get the value but not the variable name, and if I
> pass "var1" I get the name but not the value
> (as ${"var1"} isn't defined in the subroutine name space.)
>
> It doesn't seem like I can pass a string and construct a
> reference from it. Can I somehow stringify \${var1} to
> get "var1" instead of SCALAR(Hhex address)?
No, not without Devel::Peek.
> Any help appreciated. It seems as if this has to be simple,
> but the best I can currently do is pass both the string and
> the reference, which is almost as redundant as just retyping
> the whole print statement every time.
It's not trivial. You can use "eval" to get the value of an expression
given as a string (including simple variables). Then you can print
the literal expression and the value. Define two routines:
sub showval {
my ( $name, $value) = @_;
print defined $value ? "$name = $value\n" : "$name -undef-\n";
}
sub show {
join '; ', map "showval( '$_', $_)", @_;
}
(If you put them in a module, import both show() and showval().)
In a program, you may have:
my $x = 3;
my $y;
my %z = ( aaa => 123, bbb => 456 );
To see some of the values, say
eval show qw( $x $y $z{bbb} $z{gibsnich});
That prints
$x = 3
$y -undef-
$z{bbb} = 456
$z{gibsnich} -undef-
Close enough? Myself, I have it somewhere but never use it.
Anno
- Next message: Anno Siegel: "Re: getting {string} from \${string}"
- Previous message: Gunnar Hjalmarsson: "Re: Search Through List"
- In reply to: bongo_at_frii.com: "getting {string} from \${string}"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|