Array and lists
A list is an ordered collection of scalars. An array is a variable that contains a list. They’re interchangeable. But, to be accurate, the list is the data, and the array is the variable.
- There’s no limit on array length which is automatically extended.
- To refer to an entire array, just use the @ before the name of the array (and no index brackets after it), for example @myArray.
- Access array element by index: $myArray[0] .
- the last element index is $#myArray.
- array copy: when an array is copied to another array, it’s still a list assignment. Ror example:@copy = @quarry; # copy a list from one array to another
- poppop operator takes the last element off of an array and returns it:If the array is empty, pop will leave it alone, and it will return undef.
- push: adds an element (or a list of elements) to the end of an array
- The shift and unshift Operators : perform the corresponding actions on the “start” of the array
- The foreach Control Structureforeach $rock (qw/ bedrock slate lava /) {print "One rock is $rock.\n"; # Prints names of three rocks}The control variable ($rock in that example) takes on a new value from the list for each iteration. The first time through the loop, it’s "bedrock"; the third time, it’s "lava".Notes:
- The control variable is not a copy of the list element—it actually is the list element. That is, if you modify the control variable inside the loop, you’ll be modifying the element itself .
- If you omit the control variable from the beginning of the foreach loop, Perl uses its default variable, $_. For example: foreach (1..10) { # Uses $_ by default print "I can count to $_!\n"; } .
- reverse returns the reversed list; it doesn’t affect its arguments.If the return value isn’t assigned anywhere, it’s useless:reverse @fred; # doesn't change @fred@fred = reverse @fred; # puts the result back into the original array
Scalar and List Context
- As Perl is parsing your expressions, it always expects either a scalar value or a list value. What Perl expects is called the context of the expression@list = @people; # a list of three people$n = @people; # the number 3
- scalar: Forcing Scalar Context where Perl is expecting a list.print "I have ", @rocks, " rocks!\n"; # WRONG, prints all elements in @rocks arrayprint "I have ", scalar @rocks, " rocks!\n"; # Correct, gives a number
- <STDIN> in List Context ,<STDIN> returns the next line of input in a scalar context.In list context, this operator returns all of the remaining lines up to the end of file. Each line is returned as a separate element of the list. If input is not from a file but the keyboard, then you’ll normally type a Control-D† to indicate to the system that there’s no more input;For example:@lines = <STDIN>; # read standard input in list context
No comments:
Post a Comment