- Home
- Interview Questions
- Perl
block is a group of other Perl statements (which can include other blocks) surrounded by curly braces ({}). Blocks are most commonly used in conjunction with conditionals and loops, but can also be used on their own (bare blocks).
The three parts of the for loop in parentheses are
-> A loop counter initialization expression such as $i = 0
-> A test to determine how many times the loop will iterate, for example
$i < $max
-> An increment expression to bring the loop counter closer to the test, for
example, $i++.
next, last, and redo are all loop control expressions. next will stop executing the current block and start the loop at the top, including executing the test in a for or a while loop. redo is the same as next, except it restarts the block from the first statement in that block without executing the loop control test. last exits the loop altogether without retesting or reexecuting anything.
Here are a number of situations that default to the $_ if a variable isn't indicated:
while (<>) will read each line into $_ separately
chomp will remove the newline from $_
print will print $_
foreach will use $_ as the temporary variable
<> is used to input the contents of files specified on the command line (and as stored in @ARGV). <STDIN> is used to input data from standard input (usually the keyboard).
Sure! All you have to do is use the backslash operator to get the memory location of that reference. Keep in mind that if you create references to references, you’ll need to dereference them twice to get to the data at the end of the chain.
A reference is a bit of scalar data that allows you to refer to some other bit of data in an indirect way. References allow you to pass subroutine arguments by reference (retaining the structure of multiple arrays and hashes), return discrete multiple lists, as well as create and manage nested data structures such as lists of lists.
You can create a reference to an array using the backslash operator:
$ref = \@array;
Or with an anonymous array constructor:
$ref = [ 1 ..100 ];
You can dereference a reference to an array to get access to its elements by substituting
the reference where the array name is expected:
$thing = $$ref[0];
Or using arrow notation:
$thing = $ref->[0];
Changing the data a reference points to has no effect on the reference itself. The reference points to that data’s location in memory, not to the data itself.