Statically typed vs dynamically typed has been asked repeatedly on stackoverflow, for example here.
The consensus seems to be (quoting from the top answer of the above link):
A language is statically typed if the type of a variable is known at compile time.
And a dynamic language:
A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc.
Perl seems to be statically typed by this (or other common definitions of static/dynamic typing). It has 3 types: scalar, array, hash (ignoring things like references for simplicity's sake). Types are declared along with variables:
my $x = 10; # declares a scalar variable named x
my @y = (1, 2, 3); # declares an array variable named y
my %z = (one => 1, two => 2); # declares a hash variable named z
The $
, @
and %
above tell Perl which type you want; I'd count this as a form of explicit typing.
Once x
has been declared as a scalar, as above, it's impossible to store a non-scalar value in x
:
$x = @y; # x is now 3
Will convert y
to a scalar (in Perl, array to scalar conversion result in the length of the array). I blame this on weak typing (Perl very liberally allows conversions between its 3 types), rather than dynamic typing.
Whereas in most statically typed languages, such an assignment would be an error, in Perl it is ok because of implicit conversions (similar to how bool x = 1;
is fine in C/C++, but not in Java: both are statically typed, but Java is more strongly typed in this case). The only reason this conversion happened at all in Perl is because of the type of x
, which again suggests Perl is statically typed.
Another argument people have against Perl being statically typed is that floats, ints, and strings are all stored in the same type of variable (scalars). But this really has nothing to do with static or dynamic typing. Within Perl's type system (which has only 3 types), there is no difference between floats, ints and strings. These all have type scalar. This is similar to saying C89 isn't statically typed because it used the int
type to represent both ints and bools.
Obviously, this line of reasoning is ridiculous. Perl has very little in common with what most people think of as statically typed languages like C/C++, Java, OCaml, etc.
My question is, what's wrong with this line of reasoning?