next up previous contents
Next: Arrays Up: Programming in Perl Previous: Programming in Perl   Contents

Scalar datatypes

Values associated with scalar variables in Perl are either numbers or character strings. Numbers correspond to double precision floating point numbers. Variable names begin with the special character $. For instance, we could have the following assignments in a Perl program.

  $num1 = 7.3;
  $str1 = "Hello123";
  $str2 = "456World";

Variables (and their types) do not have to be declared. Moreover, the type of a variable changes dynamically, according to the type of expression that is used to assign it a value. We use normal arithmetic operators to combine numeric values. The symbol . denotes string concatenation. If a numeric value is used in a string expression, it is converted automatically to the string representation of the number. Conversely, if a string is used in a numeric expression, it is converted to a number based on the contents of the string. If the string begins with a number, the resulting value is that number. Otherwise, the value is 0. Continuing our example above, we have the following (text after # is treated as a comment in Perl).

  $num3 = $num1 + $str1;         # $num3 is now 7.3 + 0 = 7.3
  $num4 = $num1 + $str2;         # $num4 is now 7.3 + 456 = 463.3
  $str2 = $num4 . $str1;         # $str2 is now "463.3Hello123"
  $str1 = $num3 + $str2;         # $str1 is now the number 470.6
  $num1 = $num3 . "*" . $num4;   # $num1 is now the string "7.3*463.3"

By default, Perl values are made available to the program the moment they are introduced and have global scope and are hence visible throughout the program. Uninitialized variables evaluate to 0 or "" depending on whether they are used as numbers or strings. The scope of a variable can be restricted to the block in which it is defined by using the word my when it is first used.

   my $a = "foo";
   if ($some_condition) {
       my $b = "bar";
       print $a;           # prints "foo"
       print $b;           # prints "bar"
   }
   print $a;               # prints "foo"
   print $b;               # prints nothing; $b has fallen out of scope


next up previous contents
Next: Arrays Up: Programming in Perl Previous: Programming in Perl   Contents
Madhavan Mukund 2004-04-29