Learning a New Programming Language Part 3: Syntax Differences - Variable Syntax
(Page 3 of 7 )
Another minor difference in syntax can be found in the way you reference a variable in a particular language. For instance, when you declare a variable in Visual Basic you use the keyword "Dim" (meaning dimension).
Dim mynumber as integer
Javascript, on the other hand, uses the keyword "var" when declaring a variable. The var keyword shows up in PHP as well. The difference is that it is only used to declare properties in a class definition.
class myclass
{
var $size = 0;
var $weight = 0;
}
Notice also the dollar sign before each property name. This is used for variables in PHP, Perl and Ruby (only for global variables). In Perl the dollar sign is used for scalar variables (single values) and an "@" symbol is used in front of array names. If you are addressing an element of an array, however, you use the dollar sign, as this element carries a single value.
@simpsons = (Homer, Marge, Bart, Lisa, Maggy);
print "Doh! $simpsons[2] !";
Something to note about the last line of the above example is that the variable is included in the double quoted string. This is an alternate method for concatenating strings. Both Perl and PHP support this method. In Javascript this isn't possible because variables are not denoted by a preceding character, and therefore could not be distinguished from any other word in the string. In this situation an operator character is used to join strings together. Javascript and Java use the "+" operator.
var tagbegin;
var message;
var tagend;
tagbegin = "<strong>";
message = "Give me all your lupins!";
tagend = "</strong>";
alert(tagbegin + message + tagend);
/* Output would be <strong>
Give me all your lupins!</strong>*/
Ruby and Python use the "+" operator as well. Ruby can also repeat a string by using other operators.
str = "baby" * 3
# Would output baby baby baby
In PHP and Perl the operator used to concatenate strings is a period or "dot". If you are concatenating values returned from function calls with strings or variables, using the "dot" syntax in both languages is the way to go rather than putting things inside strings. Below is an example in PHP.
function identify()
{
return "We are the knights who say NEE!"
}
$tagbegin = "<strong>";
$message = "and we want a shrubbery!";
$tagend = "</strong>";
print($tagbegin.indentify().$message.$tagend);
One thing to note is that when someone is talking about the "dot syntax" in Java and Javascript, they are talking about the use of a period to separate names when addressing object properties and methods.
myObject.myMethod(otherObject.aProperty);
The TCL language uses a procedure (function) call to tcl_concat to concatenate strings. The arguments are the strings to concatenate.
Next: Defining Functions >>
More Web Hosting How-Tos Articles
More By Chris Root