This Season
 

How to Capture Standard Input in Perl

One of Perl's mottos is TIMTOWTDI (pronounced "tim toady"). It's an acronym that stands for "there is more than one way to do it." Just like everything else in Perl, there are many ways to capture standard input. Among them is a shortcut for reading all the lines in a file and doing something with them individually. Since this is a common action in Unix filter-like programs, it's used very often in Perl programs.

Related Searches:
    Difficulty:
    Moderate

    Instructions

      • 1

        Use the "angle" operator. Perl has four filehandles open by default: STDIN, STDOUT, STDERR and DATA, of which STDIN is the standard input handle, used to capture standard input.

      • 2

        Utilize the angle operator to read a single line from the filehandle passed to it, and either store in the default $_ variable or use it as the right-hand side of an assignment expression. The "angle" operator is a filehandle surrounded by less than and greater than symbols, also referred to as "angle brackets."
        "$a = ;"

      • 3

        Use the angle operator in a while loop. The angle bracket operator should be the only thing in the while loop's boolean expression when using angle brackets in a while loop. Every time the while loop is run, it'll read a line and assign it to the $_ operator. When there are no more lines to read, the while loop will end:
        "while() {
        chomp; # Chomp the $_ variable
        print; # Print the $_ variable
        }"

      • 4

        Assign the angle operator to a list. Assigning the results of the angle operator to a list is like saying "store all of the lines of this filehandle to this list." When you assign the angle operator to a list, another shortcut is performed that assigns all lines of input to the list:
        "@my_list = ;"

      • 5

        Read from the STDIN filehandle using the read function. The angle bracket reads only complete lines, and since this might not be what you want to do, the read function will let you read any amount of bytes into a variable. It takes three parameters: the filehandle, the variable to store it in and the number of bytes to read. The following example reads 10 bytes into $buffer:
        "read(STDIN,$buffer,10);"

    Tips & Warnings

    • Assigning the angle operator to a list and using the angle operator in a while loop are often called "magic syntax," because it's sometimes not obvious what they do, but they make very common actions easy.

    Related Searches

    Read Next:

    Comments

    You May Also Like

    Follow eHow

    Related Ads