Hello! I've done some Googling about this, and many sites say that "hasing" is a better alternative than using a variable name with a variable name.
I don't understand the concept of hashing, and what I'm trying to do seems small and insignifant, so I was hoping someone could help me.

I'm using a regular expression to split up my input into groups.
I want to assign each group ($1, $2, $3, and $4) to $oct1, $oct2, $oct3 and $oct4.

An array won't work due to what I'll be doing later on.

This is the for loop I thought would work. Later on, if I try to call $oct1, I can't. However, if I call $oct{1}, I can. So the code below must not be doing what I hoped it did.

for ($x = 1; $x < 5; $x++)
{ $oct{$x} = ${$x};
}

I appreciate any help.

I am not sure why you're bothering to do this. If I had more info, perhaps I could help you. You say you don't understand hashes, yet you are trying to use 2 hashes in this example. The code:

$oct{$x}

Is a keyed hash. The part between the brackets is the key. That's why $oct{1} works to retrieve something. The "1" is the key. It is not the same as $oct1 which is a scalar. It is possible to do what you wish, but there are several problems with it. First of all, $1, $2, $3, etc are reserved in perl for regex matches - that is:

/^(\s+)([1|2])/

would return what is matched in the first set of parens in $1 and what is matched in the second in $2.

It would make MUCH more sense to use a hash or a reference for your program. Perhaps you could let us know a little more what you're meaning to do and we could help you out better.

Why not do it as follows? my ($oct1, $oct2, $oct3, $oct4) = ($1, $2, $3, $4); After all, you wrote the regular expression, so you know it returns four matched groups. The sites you googled may be addressing the situation where programmers don't know how many data items they may need to save and so are thinking of creating variable names dynamically at runtime. In those situations, you can use hashes instead of scalar variables. Here is a quote from Beginning Perl which may be saying something similar to what you've been reading about using hashes instead of creating variables on-the-fly.

Edited 3 Years Ago by happygeek: fixed formatting

Hi guys. Thanks for your input. I posted the same question at devshed, and with help, I came up with this:

for ($x = 1; $x < 5; $x++)
{ ${"oct$x"} = ${"$x"}; 
}

That gave me $oct1=$1; $oct2=$2 and so on.
Additionally, I was able to use that technique several more times throughout my code as I converted to binary and did other things.
Pretty nifty technique!!

Yep that will work to do what you request. Although I'm still unclear why not use a hash. If you're happy, then good for you!

This question has already been answered. Start a new discussion instead.