Datatypes in JavaScript and Perl

Oracle PL/SQL is a strongly-typed language.
Which means when declaring the variables, we need to specify the data-type as well.
(Note: PL/SQL is not discussed here)

We do not do it either in JavaScript or Perl.
But, there is a subtle difference exists.

function fun1() {
    var x1 = "4", x2 = "2";  // though numbers, if quoted, got treated as string
    alert(x1 + x2);
    var y1 = 4, y2 = 2;
    alert(y1 + y2);
}
fun1();

In the above JavaScript snippet, the “+” operator, when one of its operand is a string, acts as a concatenation operator or else additive operator.
In Perl, we need to use two different operators for these operations.

sub fun1 {
    my $x1 = "4"; my $x2 = "2";
    print $x1 . $x2, "\n";       # concatenation operator is dot "."
    my $y1 = 4; my $y2 = 2;
    print $y1 + $y2, "\n";
}
fun1();

What if we want to add two numbers stored as a string?

function add(a, b) {
    return a + b;
}
alert(add(4, 2));
alert(add("4", "2"));
alert(add("x", "y")); // This also works

Our “add” function breaks when the quoted numbers are passed.
We can rewrite the function as below.

function add(a, b) {
    a = parseInt(a, 10);  // 2nd arg to parseInt is the radix
    b = parseInt(b, 10);
    return a + b;
}
alert(add(4, 2));
alert(add("4", "2"));
alert(add("x", "y")); // Are you serious? Want to add two strings?

parseInt function takes the stringified number as the argument and returns the actual number.
In Perl, there is no parseInt equivalent. The parsing is taken care automagically.

sub add {
    return $_[0] + $_[1];
}
print add(4, 2), "\n";
print add("4", "2"), "\n";
print add("x", "y"), "\n"; # Here the result is Zero!

Perl does more with Strings and Numbers.

sub fun2 {
    my $x = "AA98";
    $x++; print "$x\n";
    $x++; print "$x\n";
}
fun2();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s