Lesson 3: Assigning Values to Scalar Variables

  • Values can be assigned to scalar variables with the use of the assignment operator '='.
  • other assignment operators are
    • .=
    • +=
    • -=
    • *=

Scalar Assignment

## All code needs to have the complete script skeleton

## I will leave it out in the notes

1
2
3
4
5
6
# scalar_assignment.pl
# use 'my' the FIRST time you use a variable
# this is a part of the strict module
my $text = "eve";
my $num = 6;
print "Do you like $text $num?\n;"

Output:

%% ./scalar_assignment
Do you like eve 6?

Scalar reassignment

Variables are just that, VARIABLE. They can change.



Examples of reassigning values to scalar variables:

1
2
3
4
5
6
# scalar_reassignment.pl
 
my $num = 33;
print "1: $num\n";
$num = $num + 1;
print "2: $num\n";

Output:

%% ./scalar_reassignment.pl
1: 33
2: 34

Another example of scalar reassignment

1
2
3
4
5
6
7
8
9
10
11
# scalar_reassignment_2.pl
 
my $text = "The cat in the hat";
print "1: $text\n";
 
# '.' text concatenation operator
$text = $text . " " . "came back";
print "2: $text\n";
 
$text = "Ickle Me, Pickle Me, Tickle Me Too";
print "3: $text\n";

Output:

%% ./scalar_reassignment_2.pl
1: The cat in the hat
2: The cat in the hat came back
3: Ickle Me, Pickle Me, Tickle Me Too

Exercises

  1. Create a script that assigns a string to a scalar and prints the scalar.
  2. Add the reassignment of a number to the same scalar used above. Print this new value as well as the first value.

Print Friendly

3 thoughts on “Lesson 3: Assigning Values to Scalar Variables

  1. What’s the difference between Single and Double Quotes?

    • If you put a variable, such as “$text” inside of double quotes in a print statement, you will get the value of $text.
    • But if you put ‘$text’ inside of single quotes you will literally get $text.
    • The same is true for special characters like the newline “n”
    • And remember do not put operators or functions inside of quotes, even double quotes in your print statements. You will get what you typed not what the function returns

    Code: “double quotes”

    my $text = "Some line of text";
    print "$textn";
    

    Output:

    Some line of text

    Code: ‘single quotes’

    my $text = "Some line of text";
    print '$textn';
    

    Output:

    $textn
  2. Hi, I am looking for information about .= operator…What is it precise function? Is related with concatenation of strings?

    Thanks a lot,
    Cristian.

    • Hi Cristian,

      Yes, the ‘.=’ operator is related to the concatenation of strings.

      $string .= "something new";
      

      is comparable to

      $string = $string . "something new";

      This means append “something new” to what is already stored in $string and overwrite the old value of string with $string plus “something new”

Leave a Reply

Your email address will not be published. Required fields are marked *