Finding the memory usage of Perl variables My $size = scalar(keys %planet_mass_compared_to_earth) Įxample 8. This is easily done using the keys() function to return the keys as an list, and the scalar() function to return how many keys there are: Sometimes you will also want to know the number of elements in a hash. Perl has the scalar() function which forces the array into scalar context, giving you the length: While example 3 and 4 are correct, they aren't very readable or friendly to use. The example above is giving us the length of the length: the length of 5 is 1. This is because the length() function expects a scalar, so the array is forced into scalar context.Īs we saw above (example 4), an array in scalar context already gives us the length. If you try to use the length() function on an array, it won't give you the answer you are after: If you want the number of elements in the array it is best to be explicit about it (see example 6 below). The double-quotes cause Perl to flatten the array by concatenating the values into a string. Many functions, double-quotes included, treat arrays differently to scalar variables. For example, consider the following program: If you use an array in scalar context, it will return the number of elements in the array:Īpart from being confusing to read, this method can lead to some easy mistakes. My = qw(mercury venus earth mars jupiter) In Perl you can determine the subscript of the last element of an array and add 1 to it to get the number of elements in the array. # disables character semantics for the rest of the lexical # Put 'use bytes' in a closure so that it doesn't You can tell it to return the number of bytes by specifying use bytes, as in this example: This won't affect you for ASCII characters but it may if you are using Unicode characters.īy default the length() function returns the number of characters. Sometimes you want to know the number of bytes in the string, not the number of characters. This example prints the number of characters in the string $name: To determine the number of characters in an expression use the length() function: However, if you are using Unicode characters the number of characters in a string may be different to the number of bytes in the string. Generally it can mean the number of characters in a string, or the number of elements in an array or hash. Size, or length, can mean a different thing depending on what context you mean. It may be a scalar variable, or you may want to know how many elements are in an array or a hash. Quite often you will want to know the length or size of a variable. Tweet Determining length and size Introduction
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |