Lesson 4: Array Assignment


Remember, an array is a list of scalars.

array of strings

1
my @first_array = ("Went","for","a","ride","in","a","flying","shoe");

array of numbers

1
my @second_array = (22,103,1,0);

array of strings and numbers

1
my @third_array = ("ride",103,"Sally",22,0,"ride",11,"Mustang Sally");

Printing an array without using quotes

  • Prints the array without a space between elements
1
2
print "quick&ugly_1: " , @first_array , "\n";
print "quick&ugly_2: " , @second_array , "\n";

Output:

%% ./array_assignment.pl
quick&ugly_1: Wentforarideinaflyingshoe
quick&ugly_2: 2210310

Printing an array using quotes

  • Prints a space between elements
1
2
print "quick&neat_1: @first_array\n";
print "quick&neat_2: @second_array\n";

Output:

%% ./array_assignment.pl
quick&neat_1: Went for a ride in a flying shoe
quick&neat_2: 22 103 1 0

Printing an array using the join function

  • Returns a string with any character you want between each element using the join function
1
print "quick&useful_3:\n", join ("\n" , @third_array), "\n";

Output:

%% ./array_assignment.pl
quick&useful_3:
ride
103
Sally
22
0
ride
11
Mustang Sally
  • Note: qw can be used to create a quoted list.
1
2
3
# my @array = ('this','sentence','will','be','turned','into','a','list');
# same as
my @array = qw (this sentence will be turned into a list);

Exercises

  1. Create a script that contains an array of scalars.
  2. Modify the above script to print the array using quotes around your array: print "@yourArray\n";
  3. Add another line to your script in which you use the function join to transform your array into a string. Assign this new string to a new scalar variable.
  4. Print your new scalar containing your new string in addition to everything you printed above.

Print Friendly

2 thoughts on “Lesson 4: Array Assignment

Leave a Reply

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