Does Perl Have PHP-Like Dynamic Variables

Does Perl have PHP-like dynamic variables?

What you're attempting to do is called a "symbolic reference." While you can do this in Perl you shouldn't. Symbolic references only work with global variables -- not lexical (my) ones. There is no way to restrict their scope. Symbolic references are dangerous. For that reason they don't work under the strict pragma.

In general, whenever you think you need symbolic references you should use a hash instead:

my %hash;
$hash{phone} = '555-1234';
print $hash{phone};

There are a few cases where symrefs are useful and even necessary. For example, Perl's export mechanism uses them. These are advanced topics. By the time you're ready for them you won't need to ask how. ;-)

How can I assign a variable's content to a variable's name in perl?

A "hash" (or "dictionary" in some other languages) is like* an array of key-value pairs. This achieves what you describe because you can assign a value to a variable without having a fixed identifier for that variable.

*: Hashes are not arrays.

See this tutorial on Perl101. The following code snippets in this answer are taken from this site.

You can create a hash using the following syntax:

my %stooges = (
'Moe', 'Howard',
'Larry', 'Fine',
'Curly', 'Howard',
'Iggy', 'Pop',
);

Access and modify values using {}. You can use this syntax to add new values too.

print $stooges{'Iggy'}; #get existing
$stooges{'Iggy'} = 'Ignatowski'; #Overwrite
$stooges{'Shemp'} = 'Howard'; #Set new

You can delete key-value pairs using the delete function.

delete $stooges{'Curly'};

You can get a list of values or keys using the same (key)words:

my @stooge_first_names = keys %stooges;
my @stooge_last_names = values %stooges;

Why does PHP have a $ sign in front of variables?

It prevents variable names conflicting with language keywords, and allows them to be interpolated in strings.

Is the quality of a language where it's not required to declare a variables type an example of weak typing or dynamic typing

According to: http://en.wikipedia.org/wiki/Type_system#Static_and_dynamic_type_checking_in_practice

Weak typing means that a language implicitly converts (or casts) types when used.

whereas:

A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time.

So, strong/weak and static/dynamic are two different dimensions. A language will be one of strong/weak, and also one of static dynamic. For instance, Ruby and Javascript are both dynamically typed, but Ruby is strongly typed while Javascript is weakly typed. That is, in Ruby the following code with give an error:

1.9.2p290 :001 > 'a'+1
TypeError: can't convert Fixnum into String

whereas in JavaScript, you get:

> 'a'+1
>> 'a1'

So, a strongly typed language requires you to convert two variables to the same type in order to combine them (eg. using 1.to_s), while a weakly typed language will attempt to coerce the two variables into the same type using some extra built-in language logic - in JavaScript's case, combining anything with a String will convert it into a String value.

See: http://www.artima.com/weblogs/viewpost.jsp?thread=7590 for a further explanation.

Passing a variable to a Perl script from JavaScript-enabled web page

You should append an encoded version of the string to the URL without the query parameter value.

A call to encodeURIComponent encodes as hex numbers characters that may otherwise be illegal within a URL.

The + operator concatenates strings.

So you want

xmlhttp.open('GET', 'try.pl?name=' + encodeURIComponent(fileNameVar), false);

how to get sum of dynamic values from array

Beside the option to Summarize the numbers within the SQL query you may do it in PHP as well.

Avoid resetting the value on each loop step and continuously add the value to $itemVar variable:

<?php
foreach($items as $var){
$itemDisplay = $userFile->priceSelection($conn, $var, $priceQuery);
foreach($itemDisplay as $key=>$v){

//$itemVar = ''; // do not null the sum value
//Items returned that I would like to be added together
$itemVar += $v['hour_rate'];

//$values = intval($itemVar);

}
}
print_r($itemVar); // print final value

EDIT after OP update

I see two issues in the updated OP code.

  1. the data in the variable $day_rate is set directly and only within the nested foreach loop so this variable keeps the very last value that is set each time the else - else condition is met AND it is the only place where the variable is initiated. This could make some troubles in final calculation.

  2. the $itemVar variable is incrementally calculating its total sum in each loop however the $day_rate is not and more over the problem mentioned in first point. You may need to make a sum of that value as well what you can achieve with this: $day_rate = $v['day_rate'];

  3. potential problem might be the comparison of (xxx == '1') as the PHP dynamically works with the variable entity it will take and convert the value of xxx to most probable to an integer and then converts the string of '1' to the integer as well befor the comparison is made. As an example gues how is compared var_dump(true == '1'); true or false, huh?

Note it is going to be XY problem since the whole structure starts not making any sense to me.


Last EDIT
As general purpose tip for understanding what your code is doing I would recommend any kind of debugger where you can see live status of any variable while the script is processing. Debugging in PHP

Or very simple way of debugging that is simple printing the variable content so you can get at least some idea how to data are calculated.

And of course Always debug your scripts with enabled PHP Error Reporting!

// Counters for 
$itemsCounter = 0;
$displayCounter = 0;
foreach($items as $var){
$itemDisplay = $userFile->priceSelection($conn, $var, $priceQuery);
foreach($itemDisplay as $key=>$v){
// Debug current variables rows and $v
echo "Row $itemsCounter::$displayCounter; key=$key;". print_r($v, true);
//Edits added
$itemVar += $v['hour_rate'];
if($hours >= 3){ // WHERE do you get the $hours? Sould it be $v['hour_rate']?
if($v['hourly_rental'] == '1'){
$hours -= 2;
$itemVar += $v['day_rate'] * $hours;
}else{
$itemVar += $v['day_rate'];
}
// Debug current variable $itemVar
echo "itemVar=$itemVar;"
}else{
if($v['hourly_rental'] == '1'){
$itemVar += $v['day_rate'];
}else{
$day_rate = $v['day_rate'];

print_r($day_rate);
}
// Debug current variable $itemVar and new $day_rate
echo "itemVar=$itemVar;day_rate=$day_rate;"
}
$displayCounter++; // iterrate the inner counter
}
// iterrate the counter
$itemsCounter++;
// reset the inner counter for next loop
$displayCounter = 0;
// Debug inserts new line
echo PHP_EOL;
}

$totalPrice = $itemVar + $day_rate + $delivery_cost;

In Perl, can refer to an array using its name?

Possible? Yes. Recommended? No. In general, using symbolic references is bad practice. Instead, use a hash to hold your arrays. That way you can look them up by name:

sub print_species_names {
my $species = shift;
my %animals = (
cats => [qw(Jeffry Owen)],
dogs => [qw(Duke Lassie)],
);
if (my $array = $animals{$species}) {
print "$_\n" for @$array
}
else {
die "species '$species' not found"
}
}

If you want to reduce that even more, you could replace the if/else block with:

    print "$_\n" for @{ $animals{$species}
or die "species $species not found" };

Replace with dynamic variable in preg_replace

You may use preg_replace_callback like this:

$array = ['name' => 'John', 'email' => 'john@gmail.com'];
$string = 'Hi [[name]], your email is [[email]]';
echo preg_replace_callback('/\[\[(.*?)]]/', function ($m) use ($array) {
return isset($array[$m[1]]) ? $array[$m[1]] : $m[0];
}, $string);

See PHP demo.

Details

  • '/\[\[(.*?)]]/' matches [[...]] substrings putting what is inside the brackets into Group 1
  • $m holds the match object
  • use ($array) allows the callback to access $array variable
  • isset($array[$m[1]]) checks if there is a value corresponding to the found key in the $array variable. If it is found, the value is returned, else, the found match is pasted back.


Related Topics



Leave a reply



Submit