1. Scalar variables
Scalar variables hold both strings and numbers. Strings and numbers are inter-changable, but the variables should not start with a number and the variable $_ is special. For example:
$variable1 = 10; or
$variable2 = 'test';
The operations and assignment are the same as C. I found out this on the website, which can help us to understand the operation.
Perl uses all the usual C arithmetic operators:
$a = 1 + 2; # Add 1 and 2 and store in $a
$a = 3 - 4; # Subtract 4 from 3 and store in $a
$a = 5 * 6; # Multiply 5 and 6
$a = 7 / 8; # Divide 7 by 8 to give 0.875
$a = 9 ** 10; # Nine to the power of 10
$a = 5 % 2; # Remainder of 5 divided by 2
++$a; # Increment $a and then return it
$a++; # Return $a and then increment it
--$a; # Decrement $a and then return it
$a--; # Return $a and then decrement it
and for strings Perl has the following among others:
$a = $b . $c; # Concatenate $b and $c
$a = $b x $c; # $b repeated $c times
To assign values Perl includes
$a = $b; # Assign $b to $a
$a += $b; # Add $b to $a
$a -= $b; # Subtract $b from $a
$a .= $b; # Append $b onto $a
2. Array Variable
Array variables are prefixed by an @ symbol. The statement
@variable = ("number1", "number2", "number3");
assigns a three element list to the array variable @variable. To access each item,
$variable[0] will returns number1. Notice that the @ has changed to a $.
Array assignment functions are put and pop. Here are some examples:
push(@array1, "item3", "item4");
push(@array1, ("item3", "item4"));
push(@array1, @array2);
The push function returns the length of the new list.
To remove the last item from a list and return it use the pop function.
$item1 = pop(@array1);
Now $item1 is the last item in @array1 and the @array1 has all the items except item1.
We can also assign an array to a scalar variable.
$item1 = @array1;
assigns the length of @array1
$item1 = "@array1";
turns the list into a string with a space between each element.
Arrays can also be used to make multiple assignments to scalar variables:
($a, $b) = ($c, $d); # Same as $a=$c; $b=$d;
($a, $b) = @food; # $a and $b are the first two
# items of @food.
($a, @somefood) = @food; # $a is the first item of @food
# @somefood is a list of the
# others.
Sunday, July 19, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment