Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials

initialize all elements of an array with the same value

( categories: | )

A useful method to initialize all the elements of an array with the same value is with the 'x' repetition operator.

The 'x' operator is mostly used in scalar context to build a string with a repeated pattern but, when used in a list context, it allows to set all the elements of an array with the same value.

Examples:
#-- initialixe @array with 50 zeroes
@array = 0 x 50;
 
#-- reset all elements to value '1'
@array = (1) x @array


align here-documents in the source code

( categories: )

'here-document is a very handy Perl operator that allows to easily define multiline strings. Unfortunately, most of the times, the inclusion of a here-document string breaks the indentation level of the source code like in this example:

  while ( $something )
  {
    if ( $anything )
    {
      print <<EOF;
there goes the nicely formatted source code
because of this here-document
string
EOF
 
      #-- continue with the script


range operators

( categories: )

The range operators are .. (two dots) and ... (three dots).

In list context both operators behave in the same way, returning a list of values counting from the left value to the right value (it even works on strings).

They're very useful for creating loops, slicing arrays, etc.

Example:

printf "Line %d\n", ++$i foreach ( 1 .. 10 );

In scalar context, they emulate the behaviour of the line range operator of sed.
To do this, the operator returns a boolean value, and this value is maintained across the duration of the routine that has the operator.


comparison operators

( categories: )

You have to use different comparison operators, depending whether you want to compare arguments numerically or stringwise:

- numerical comparison operators

== returns true if both arguments are numerically equal
!= returns true if both arguments are numerically different
 <=>  returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument
< returns true if left argument is numerically smaller than right argument
> returns true if left argument is numerically bigger than right argument
<= returns true if left argument is numerically smaller or equal than right argument
>= returns true if left argument is numerically bigger or equal than right argument

precedence of operators

( categories: )

The list is ordered from highest precedence to lowest:


Syndicate content