LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl Script: Variable Names composed of Variables (https://www.linuxquestions.org/questions/programming-9/perl-script-variable-names-composed-of-variables-411766/)

wwnexc 02-04-2006 10:22 PM

Perl Script: Variable Names composed of Variables
 
Hi,

I am pretty new to perl, and i have just begun writing a small sudoku solver.

I am wondering if there is a function which allows you so combine two variables and use them as the name for an other variable.

For example:
$i=55;
$n=12;
$i,$n="whatever the variable should contain";

The $i,$n= are supposed to be 5512. Is there any way to do such a thing? Or is there a way to get 3 dimensional matrices or other arrays with more than one dimension? If there are such things, what do they look like??

Thanks!!

bulliver 02-05-2006 04:11 AM

Quote:

Or is there a way to get 3 dimensional matrices or other arrays with more than one dimension? If there are such things, what do they look like??
Sure. You can create a hash of arrays:
Code:

%hash_of_array = (
foo => [1, 2, 3],
bar => [4, 5, 6],
baz => [7, 8, 9],
);

or even hashes of hashes:
Code:

%hash_of_hash = (
foo => {
  x => 1,
  y => 2,
  },
bar => {
  x => 3,
  y => 4,
  },
);

You can pretty much nest any structure into any other (except simple scalars) to any arbitrary depth.

bigearsbilly 02-05-2006 06:34 AM

you can't have a comma, in a perl variable name and you can't start with a digit.
You should use bullivers suggestion.

However FYI:
You can do things like this though:

Code:

$ perl
$x="hello";
$$x = "goodbye";
print "$x, $hello\n";
hello, goodbye

combining two would need an intermediate step...

Code:

$ perl
$i=a55;
$n=b12;
$x="${i}_$n";
$$x = "combined";
print $a55_b12;
combined$

though I would say this is horrible and ugly.
Also it is a whole world of bugs waiting to happen!

wwnexc 02-05-2006 10:58 AM

Thanks for all your help.

I went with bulliver's method. I now am able to store each possible value in a list, which of each field corresponds to a list of possibilities.

Bigbearsbilly, you are right - it works, but it's only bugs waiting to happen. I am probably not going to use this method, even thoug it looks interesting.

bigearsbilly 02-06-2006 03:47 AM

You can do it with funcs. Can be very useful.
E.g. I was writing a server and wanted a list of valid commands and help text for each
but also it's easy to lose track. So I did:

Code:

@command_list = sort qw( DUMMY DUMP ADD DEL WHO DROP LOAD COUNT QUIT HELP );
foreach my $c (@command_list) {

    unless (defined &$c) {
        warn "WARNING:command $c not defined!" ;
        *$c = sub { print OUT "?function $c?:not defined" };
    }

so you get a dummy command defined with a warning.


All times are GMT -5. The time now is 01:14 PM.