[Chapter 3] 3.2.14 chop
Author: Larry Wall, Tom Christiansen & Randal L. Schwartz
Date: 1999-07-02T01:48:01Z

#

| Chapter 3 Functions |

### 3.2.14 chop

    chop VARIABLE
    chop LIST
    chop

This function chops off the last character of a string and returns the character chopped. The chop operator is used primarily to remove the newline from the end of an input record, but is more efficient than `s/\n$//`. If `VARIABLE` is omitted, the function chops the $_ variable. For example:

    while (<PASSWD>) {
        chop;   # avoid \n on last field
        @array = split /:/;
        ...
    }

If you chop a `LIST`, each string in the list is chopped:

    @lines = `cat myfile`;
    chop @lines;

You can actually chop anything that is an lvalue, including an assignment:

    chop($cwd = `pwd`);
    chop($answer = <STDIN>);

Note that this is different from:

    $answer = chop($tmp = <STDIN>);  # WRONG

which puts a newline into `$answer`, because chop returns the character chopped, not the remaining string (which is in `$tmp`). One way to get the result intended here is with substr:

    $answer = substr <STDIN>, 0, -1;

But this is more commonly written as:

    chop($answer = <STDIN>);

To chop more than one character, use substr as an lvalue, assigning a null string. The following removes the last five characters of `$caravan`:

    substr($caravan, -5) = "";

The negative subscript causes substr to count from the end of the string instead of the beginning.

3.2.13 chomp |  | 3.2.15 chown