Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
Don't ask to ask, just ask
 
PerlMonks  

Re: Access variable names

by Roger (Parson)
on Sep 01, 2005 at 08:07 UTC ( #488321=note: print w/ replies, xml ) Need Help??


in reply to Access variable names

It is not possible to know the variable name of the variable passed into the subroutine, you need to tell it the name of the varaibles.

Just a minor modification to your code will make it work - just pass in the variable name in csv format.

#!/usr/bin/perl use strict; use warnings; sub defnz { my @names = split /,/, shift; my %vars; @vars{@names} = @_; for my $item (@names) { if (!defined($vars{$item})) { print STDERR "$item is not defined\n"; return; } elsif ($vars{$item} eq '') { print STDERR "$item is empty\n"; return; } } print STDOUT "All scalars defined and non-empty\n"; return 1; # all items in list defined and non-empty } my ($foo,$bar,$baz) = ("FOO","BAR","BAZ"); defnz('$foo,$bar,$baz', $foo,$bar,$baz); ($foo,$bar,$baz) = ("FOO","BAR",""); defnz('$foo,$bar,$baz', $foo,$bar,$baz); ($foo,$bar,$baz) = ("FOO",undef,""); defnz('$foo,$bar,$baz', $foo,$bar,$baz); __END__ output is: All scalars defined and non-empty $baz is empty $bar is not defined
Simpler still, you can use Data::Dumper to inspect the variables.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub defnz { my @names = split /,/, shift; my %vars; @vars{@names} = @_; for my $item (@names) { if (!defined($vars{$item}) || $vars{$item} eq '') { print STDERR Dumper(\%vars); return; } } print STDOUT "All scalars defined and non-empty\n"; return 1; # all items in list defined and non-empty } my ($foo,$bar,$baz) = ("FOO","BAR","BAZ"); defnz('$foo,$bar,$baz', $foo,$bar,$baz); ($foo,$bar,$baz) = ("FOO","BAR",""); defnz('$foo,$bar,$baz', $foo,$bar,$baz); ($foo,$bar,$baz) = ("FOO",undef,""); defnz('$foo,$bar,$baz', $foo,$bar,$baz); __END__ output: All scalars defined and non-empty $VAR1 = { '$foo' => 'FOO', '$baz' => '', '$bar' => 'BAR' }; $VAR1 = { '$foo' => 'FOO', '$baz' => '', '$bar' => undef };


Comment on Re: Access variable names
Select or Download Code
Re^2: Access variable names
by Ovid (Cardinal) on Sep 01, 2005 at 16:44 UTC

    It is not possible to know the variable name of the variable passed into the subroutine ...

    With Perl out of the box, that's true. Otherwise, use PadWalker.

    Cheers,
    Ovid

    New address of my CGI Course.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://488321]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2014-04-21 02:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (489 votes), past polls