Friday, 19 March 2021

perl data structures tutorial - part1

Perl provides a rich set of data structures that can be used to store and manipulate data. In this tutorial, I'll cover the most commonly used data structures in Perl, along with code examples.

Arrays

Arrays are ordered lists of scalar values. To declare an array, you use the @ symbol followed by the array name. Here's an example:

@my_array = (1, 2, 3, 4, 5);


You can access individual elements of the array using the array name followed by the index of the element in square brackets. Here's an example:

print $my_array[0]; # prints 1


You can also use the scalar function to get the number of elements in an array:

print scalar(@my_array); # prints 5



Hashes

Hashes are collections of key/value pairs. To declare a hash, you use the % symbol followed by the hash name. Here's an example:

%my_hash = ('apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange');


You can access individual values in the hash using the hash name followed by the key in curly braces. Here's an example:

print $my_hash{'apple'}; # prints red



You can also use the keys and values functions to get the keys and values of a hash:

@keys = keys %my_hash; @values = values %my_hash;




References

References are variables that refer to other variables, such as arrays or hashes. To create a reference, you use the backslash () operator. Here's an example:

@my_array = (1, 2, 3, 4, 5); $my_array_ref = \@my_array;



You can access the elements of the referenced array using the arrow operator (->). Here's an example:

print $my_array_ref->[0]; # prints 1



You can also create references to hashes:

%my_hash = ('apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange'); $my_hash_ref = \%my_hash;



And access the values of the referenced hash using the arrow operator:

print $my_hash_ref->{'apple'}; # prints red



Arrays of Arrays

Arrays of arrays are arrays that contain other arrays as elements. To declare an array of arrays, you use the @ symbol followed by the array name, and each element of the array is itself an array. Here's an example:

@my_array_of_arrays = ( [1, 2, 3], [4, 5, 6], [7, 8, 9] );




You can access the individual elements of the arrays using the array index and the element index. Here's an example:

print $my_array_of_arrays[1][2]; # prints 6



Hashes of Hashes

Hashes of hashes are hashes that contain other hashes as values. To declare a hash of hashes, you use the % symbol followed by the hash name, and each value of the hash is itself a hash. Here's an example:

%my_hash_of_hashes = ( 'fruit' => { 'apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange' }, 'vegetable' => { 'carrot' => 'orange', 'spinach' => 'green' } );



You can access the individual values of the hashes using the hash key and the hash element key. Here's an example:

print $my_hash_of_hashes{'fruit'}{'apple'}; # prints red



These are the most commonly used data structures in Perl. By combining these data structures with Perl's powerful built-in functions and operators, you can easily manipulate and process data in your Perl programs.

Here are some additional examples of working with these data structures in Perl:

Arrays


# declaring an array @fruits = ('apple', 'banana', 'orange', 'grape'); # adding an element to the end of the array push(@fruits, 'strawberry'); # removing an element from the end of the array pop(@fruits); # adding an element to the beginning of the array unshift(@fruits, 'kiwi'); # removing an element from the beginning of the array shift(@fruits); # accessing a range of elements in the array @slice = @fruits[1..3]; # looping through an array foreach $fruit (@fruits) { print "$fruit\n"; }



Hashes

# declaring a hash %colors = ('red' => 'apple', 'yellow' => 'banana', 'orange' => 'orange'); # adding a key/value pair to the hash $colors{'purple'} = 'grape'; # removing a key/value pair from the hash delete $colors{'yellow'}; # checking if a key exists in the hash if (exists $colors{'green'}) { print "Green fruit found: $colors{'green'}\n"; } else { print "No green fruit found.\n"; } # looping through a hash while (($color, $fruit) = each %colors) { print "$color: $fruit\n"; }



References


# creating a reference to an array @numbers = (1, 2, 3, 4, 5); $numbers_ref = \@numbers; # looping through the referenced array foreach $num (@{$numbers_ref}) { print "$num\n"; } # creating a reference to a hash %person = ('name' => 'John', 'age' => 30, 'city' => 'New York'); $person_ref = \%person; # accessing the values of the referenced hash print "Name: $person_ref->{'name'}\n"; print "Age: $person_ref->{'age'}\n"; print "City: $person_ref->{'city'}\n";




Arrays of Arrays


# declaring an array of arrays @matrix = ( [1, 2, 3], [4, 5, 6], [7, 8, 9] ); # accessing an element in the array of arrays print $matrix[1][2]; # prints 6




Hashes of Hashes


# declaring a hash of hashes %employees = ( 'John' => { 'age' => 30, 'salary' => 50000, 'department' => 'Sales' }, 'Jane' => { 'age' => 40, 'salary' => 60000, 'department' => 'Marketing' } ); # accessing a value in the hash of hashes print $employees{'John'}{'salary'}; # prints 50000




These examples should give you a good understanding of how to work with the most commonly used data structures in Perl. With these data structures and the many powerful functions and operators built into Perl, you can easily manipulate and process data in your programs.

Arrays of Hashes

# declaring an array of hashes @employees = ( {'name' => 'John', 'age' => 30, 'salary' => 50000}, {'name' => 'Jane', 'age' => 40, 'salary' => 60000} ); # accessing a value in the array of hashes print $employees[0]{'salary'}; # prints 50000



Hashes of Arrays


# declaring a hash of arrays %fruits = ( 'red' => ['apple', 'cherry', 'strawberry'], 'yellow' => ['banana', 'lemon', 'pineapple'] ); # accessing a value in the hash of arrays print $fruits{'red'}[1]; # prints cherry




References to Hashes of Arrays

# creating a reference to a hash of arrays %basket = ( 'apples' => [3, 'red'], 'bananas' => [2, 'yellow'], 'oranges' => [4, 'orange'] ); $basket_ref = \%basket; # looping through the referenced hash of arrays while (($fruit, $info) = each %{$basket_ref}) { print "$fruit: $info->[0] $info->[1]\n"; }




These are some additional examples of working with complex data structures in Perl. With a good understanding of how to use these data structures, you can write more complex and powerful Perl programs.

Slices of Arrays and Hashes


# creating an array and a hash @numbers = (1, 2, 3, 4, 5); %colors = ('red' => 'apple', 'yellow' => 'banana', 'orange' => 'orange'); # creating slices of the array and hash @num_slice = @numbers[1..3]; %color_slice = %colors{'red', 'orange'}; # printing the slices print "@num_slice\n"; # prints 2 3 4 while (($color, $fruit) = each %color_slice) { print "$color: $fruit\n"; }




Sorting Arrays and Hashes

# creating an array and a hash @fruits = ('apple', 'banana', 'orange', 'grape'); %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); # sorting the array and hash @sorted_fruits = sort @fruits; %sorted_ages = sort {$ages{$a} <=> $ages{$b}} %ages; # printing the sorted array and hash print "@sorted_fruits\n"; # prints apple banana grape orange while (($name, $age) = each %sorted_ages) { print "$name: $age\n"; }




These examples show how to use slices and sorting functions in Perl to manipulate data structures. With these tools, you can perform more complex data manipulation and processing tasks in your Perl programs.


Merging and Combining Arrays and Hashes


# merging two arrays @array1 = (1, 2, 3); @array2 = (4, 5, 6); @merged_array = (@array1, @array2); print "@merged_array\n"; # prints 1 2 3 4 5 6 # combining two hashes %hash1 = ('John' => 30, 'Jane' => 40); %hash2 = ('Bob' => 25, 'Alice' => 35); %combined_hash = (%hash1, %hash2); while (($name, $age) = each %combined_hash) { print "$name: $age\n"; }




Deleting Elements from Arrays and Hashes


# creating an array and a hash @fruits = ('apple', 'banana', 'orange', 'grape'); %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); # deleting elements from the array and hash splice(@fruits, 1, 2); # removes 'banana' and 'orange' delete $ages{'Bob'}; # printing the updated array and hash print "@fruits\n"; # prints apple grape while (($name, $age) = each %ages) { print "$name: $age\n"; }



These examples demonstrate how to merge and combine data structures as well as how to delete elements from them in Perl. With these tools, you can create more complex and flexible data structures for your programs


Iterating over Multidimensional Arrays and Hashes


# creating a multidimensional array @matrix = ( [1, 2, 3], [4, 5, 6], [7, 8, 9] ); # iterating over the multidimensional array foreach $row (@matrix) { foreach $element (@$row) { print "$element "; } print "\n"; } # creating a nested hash %employees = ( 'John' => {'age' => 30, 'salary' => 50000}, 'Jane' => {'age' => 40, 'salary' => 60000} ); # iterating over the nested hash while (($name, $info) = each %employees) { print "$name:\n"; while (($key, $value) = each %$info) { print "\t$key: $value\n"; } }




These examples demonstrate how to iterate over multidimensional arrays and hashes in Perl. With this knowledge, you can traverse complex data structures and perform operations on their elements.

Copying Arrays and Hashes


# creating an array and a hash @fruits = ('apple', 'banana', 'orange', 'grape'); %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); # copying the array and hash @new_fruits = @fruits; %new_ages = %ages; # modifying the original array and hash pop @fruits; # removes 'grape' $ages{'Alice'} = 35; # printing both the original and copied data structures print "@fruits\n"; # prints apple banana orange print "@new_fruits\n"; # prints apple banana orange grape while (($name, $age) = each %ages) { print "$name: $age\n"; # prints John 30 Jane 40 Bob 25 Alice 35 } while (($name, $age) = each %new_ages) { print "$name: $age\n"; # prints John 30 Jane 40 Bob 25 }




These examples show how to copy arrays and hashes in Perl. By copying data structures, you can create new ones that are independent of the original and modify them without affecting the original.

Sorting Arrays and Hashes


# sorting an array @fruits = ('banana', 'orange', 'apple', 'grape'); @sorted_fruits = sort @fruits; print "@sorted_fruits\n"; # prints apple banana grape orange # sorting a hash by keys %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); foreach $name (sort keys %ages) { $age = $ages{$name}; print "$name: $age\n"; } # sorting a hash by values %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); foreach $name (sort { $ages{$a} <=> $ages{$b} } keys %ages) { $age = $ages{$name}; print "$name: $age\n"; }




These examples show how to sort arrays and hashes in Perl. By sorting data structures, you can arrange their elements in a specific order and make them more readable or useful for your program.


Searching Arrays and Hashes


# searching an array @fruits = ('banana', 'orange', 'apple', 'grape'); if ('apple' ~~ @fruits) { print "Found 'apple' in the array\n"; } else { print "Could not find 'apple' in the array\n"; } # searching a hash by keys %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); if (exists $ages{'Bob'}) { print "Found 'Bob' in the hash\n"; } else { print "Could not find 'Bob' in the hash\n"; } # searching a hash by values %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); $search_age = 30; while (($name, $age) = each %ages) { if ($age == $search_age) { print "Found $name with age $age\n"; } }




These examples show how to search arrays and hashes in Perl. By searching data structures, you can find specific elements or values and perform operations on them.


Merging Arrays and Hashes


# merging two arrays @fruits1 = ('apple', 'banana'); @fruits2 = ('orange', 'grape'); @all_fruits = (@fruits1, @fruits2); print "@all_fruits\n"; # prints apple banana orange grape # merging two hashes %ages1 = ('John' => 30, 'Jane' => 40); %ages2 = ('Bob' => 25, 'Alice' => 35); %all_ages = (%ages1, %ages2); while (($name, $age) = each %all_ages) { print "$name: $age\n"; }




These examples show how to merge arrays and hashes in Perl. By merging data structures, you can combine their elements into a new data structure and perform operations on them.


Accessing Nested Data Structures


# accessing a nested array @fruits = ( ['apple', 'banana'], ['orange', 'grape'] ); print $fruits[0][0]; # prints 'apple' print $fruits[1][1]; # prints 'grape' # accessing a nested hash %ages = ( 'John' => { 'age' => 30, 'height' => 170 }, 'Jane' => { 'age' => 40, 'height' => 165 }, ); print $ages{'John'}{'age'}; # prints 30 print $ages{'Jane'}{'height'}; # prints 165



These examples show how to access nested data structures in Perl. By accessing nested data structures, you can extract specific elements or values from them and perform operations on them.


Manipulating Data Structures


# adding elements to an array @fruits = ('apple', 'banana'); push @fruits, 'orange'; print "@fruits\n"; # prints apple banana orange # deleting elements from an array @fruits = ('apple', 'banana', 'orange'); pop @fruits; print "@fruits\n"; # prints apple banana # adding elements to a hash %ages = ('John' => 30, 'Jane' => 40); $ages{'Bob'} = 25; while (($name, $age) = each %ages) { print "$name: $age\n"; } # deleting elements from a hash %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); delete $ages{'Bob'}; while (($name, $age) = each %ages) { print "$name: $age\n"; }





These examples show how to manipulate data structures in Perl. By manipulating data structures, you can add or delete elements or values from them and perform other operations on them.

Iterating over Data Structures


# iterating over an array @fruits = ('apple', 'banana', 'orange'); foreach $fruit (@fruits) { print "$fruit\n"; } # iterating over a hash by keys %ages = ('John' => 30, 'Jane' => 40); foreach $name (keys %ages) { print "$name: $ages{$name}\n"; } # iterating over a hash by values %ages = ('John' => 30, 'Jane' => 40); foreach $age (values %ages) { print "$age\n"; }



These examples show how to iterate over data structures in Perl. By iterating over data structures, you can access each element or value in the data structure and perform operations on them.


Sorting Data Structures


# sorting an array @fruits = ('orange', 'banana', 'apple'); @sorted_fruits = sort @fruits; print "@sorted_fruits\n"; # prints apple banana orange # sorting a hash by keys %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); foreach $name (sort keys %ages) { print "$name: $ages{$name}\n"; } # sorting a hash by values %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); foreach $name (sort { $ages{$a} <=> $ages{$b} } keys %ages) { print "$name: $ages{$name}\n"; }



These examples show how to sort data structures in Perl. By sorting data structures, you can put their elements or values in order and perform operations on them.


Filtering Data Structures


# filtering an array @numbers = (1, 2, 3, 4, 5); @even_numbers = grep { $_ % 2 == 0 } @numbers; print "@even_numbers\n"; # prints 2 4 # filtering a hash by keys %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); %filtered_ages = map { $_ => $ages{$_} } grep { $_ ne 'Bob' } keys %ages; while (($name, $age) = each %filtered_ages) { print "$name: $age\n"; } # filtering a hash by values %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); %filtered_ages = (); foreach $name (keys %ages) { if ($ages{$name} > 30) { $filtered_ages{$name} = $ages{$name}; } } while (($name, $age) = each %filtered_ages) { print "$name: $age\n"; }




These examples show how to filter data structures in Perl. By filtering data structures, you can extract elements or values that meet certain conditions and perform operations on them.


Merging Data Structures


# merging two arrays @fruits1 = ('apple', 'banana'); @fruits2 = ('orange', 'mango'); @merged_fruits = (@fruits1, @fruits2); print "@merged_fruits\n"; # prints apple banana orange mango # merging two hashes %hash1 = ('John' => 30, 'Jane' => 40); %hash2 = ('Bob' => 25, 'Tom' => 35); %merged_hash = (%hash1, %hash2); while (($name, $age) = each %merged_hash) { print "$name: $age\n"; }



These examples show how to merge data structures in Perl. By merging data structures, you can combine them into a single data structure and perform operations on the merged data structure.


Flattening Nested Data Structures


# flattening a nested array @numbers = (1, 2, [3, 4], [5, [6, 7]]); @flat_numbers = (); foreach $element (@numbers) { if (ref($element) eq 'ARRAY') { push @flat_numbers, @$element; } else { push @flat_numbers, $element; } } print "@flat_numbers\n"; # prints 1 2 3 4 5 6 7 # flattening a nested hash %ages = ('John' => 30, 'Jane' => {'Bob' => 25, 'Tom' => 35}); %flat_ages = (); foreach $name (keys %ages) { if (ref($ages{$name}) eq 'HASH') { foreach $subname (keys %{$ages{$name}}) { $flat_ages{"$name.$subname"} = $ages{$name}{$subname}; } } else { $flat_ages{$name} = $ages{$name}; } } while (($name, $age) = each %flat_ages) { print "$name: $age\n"; }



These examples show how to flatten nested data structures in Perl. By flattening nested data structures, you can convert them into a single-level data structure and perform operations on the flattened data structure.


Sorting Data Structures


# sorting an array @numbers = (5, 2, 4, 1, 3); @sorted_numbers = sort {$a <=> $b} @numbers; print "@sorted_numbers\n"; # prints 1 2 3 4 5 # sorting a hash by keys %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); foreach $name (sort keys %ages) { print "$name: $ages{$name}\n"; } # sorting a hash by values %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); foreach $name (sort {$ages{$a} <=> $ages{$b}} keys %ages) { print "$name: $ages{$name}\n"; }




These examples show how to sort data structures in Perl. By sorting data structures, you can arrange their elements or values in a certain order and perform operations on the sorted data structure.


Filtering Data Structures

# filtering an array @numbers = (1, 2, 3, 4, 5); @even_numbers = grep {$_ % 2 == 0} @numbers; print "@even_numbers\n"; # prints 2 4 # filtering a hash by keys %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); @selected_names = ('John', 'Bob'); %filtered_ages = (); foreach $name (@selected_names) { $filtered_ages{$name} = $ages{$name}; } while (($name, $age) = each %filtered_ages) { print "$name: $age\n"; } # filtering a hash by values %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); @selected_ages = (25, 30); %filtered_ages = (); foreach $name (keys %ages) { if (grep {$_ == $ages{$name}} @selected_ages) { $filtered_ages{$name} = $ages{$name}; } } while (($name, $age) = each %filtered_ages) { print "$name: $age\n"; }




These examples show how to filter data structures in Perl. By filtering data structures, you can select certain elements or values that match a certain condition and perform operations on the filtered data structure.


Merging Data Structures


# merging two arrays @numbers1 = (1, 2, 3); @numbers2 = (4, 5, 6); @merged_numbers = (@numbers1, @numbers2); print "@merged_numbers\n"; # prints 1 2 3 4 5 6 # merging two hashes %hash1 = ('John' => 30, 'Jane' => 40); %hash2 = ('Bob' => 25, 'Tom' => 35); %merged_hash = (%hash1, %hash2); while (($name, $age) = each %merged_hash) { print "$name: $age\n"; }



These examples show how to merge data structures in Perl. By merging data structures, you can combine the elements or values of two or more data structures and perform operations on the merged data structure.


Converting Data Structures


# converting an array to a hash @numbers = (1, 2, 3, 4, 5); %hash = map {$_ => 1} @numbers; while (($key, $value) = each %hash) { print "$key: $value\n"; } # converting a hash to an array %ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25); @names = keys %ages; @ages = values %ages; print "@names\n"; # prints John Jane Bob print "@ages\n"; # prints 30 40 25 # converting a string to an array $string = "This is a test string"; @words = split(/ /, $string); print "@words\n"; # prints This is a test string # converting an array to a string @words = ("This", "is", "a", "test", "string"); $string = join(" ", @words); print "$string\n"; # prints This is a test string



These examples show how to convert data structures in Perl. By converting data structures, you can change the format of the data and perform operations on the converted data structure.


Sorting Data Structures


# sorting an array
@numbers = (5, 1, 4, 2, 3);
@sorted_numbers = sort {$a <=> $b} @numbers;
print "@sorted_numbers\n";  # prints 1 2 3 4 5

# sorting a hash by keys
%ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25);
foreach $name (sort keys %ages) {
  $age = $ages{$name};
  print "$name: $age\n";
}

# sorting a hash by values
%ages = ('John' => 30, 'Jane' => 40, 'Bob' => 25);
@sorted_names = sort {$ages{$a} <=> $ages{$b}} keys %ages;
foreach $name (@sorted_names) {
  $age = $ages{$name};
  print "$name: $age\n";
}



These examples show how to sort data structures in Perl. By sorting data structures, you can order the elements or values of the data structure and perform operations on the sorted data structure.


In this tutorial, we covered various data structures in Perl, including arrays, hashes, and scalar variables. We also looked at how to manipulate and access data structures, as well as how to perform common operations such as iterating, merging, converting, and sorting.

Perl's data structures provide a powerful and flexible way to store, access, and manipulate data. By mastering Perl's data structures, you can write efficient and effective code for a wide range of programming tasks.

Labels:

0 Comments:

Post a Comment

Note: only a member of this blog may post a comment.

<< Home