$Variable_B has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys, I have a problem with my experiments with the chop command. I am still a newbie like us all at perl but a extreme newbie at that. So please keep it simple. I understand the concept of chop but I am having trouble putting it into context. I am trying this and it won't work. If someone could tell me what I was doing wrong and then tell me how to fix it without giving it away I would be gratefully in debt to the mam/sir. Here is the code that won't work...yet.

#!/usr/bin/perl $a=fredd; print chop "$a"

I want this to cut the extra "d" off of the scalar $a=fredd. What am I doing wrong?

-Variable_B

Replies are listed 'Best First'.
Re: "Chop" problems
by hossman (Prior) on Oct 12, 2002 at 06:06 UTC
    1. chop returns the character choped off, so if you expect it to print "fred" it won't.
    2. chop "$a" isn't the same thing as chop $a. You have to pass a variable to chop, so it can modify it -- what you are passing it is a string constant that you made which contains the variable.
      Good point, hossman. The original poster could have seen this had he used -w in his invocation of perl. I just tried it, and got this error:

      Can't modify constant item in chop at test.pl line 2, near ""foo";"

      thor

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: "Chop" problems
by hossman (Prior) on Oct 12, 2002 at 06:10 UTC

    PS, perldoc is your friend...

    
    laptop:~> perldoc -f chop
    
    chop VARIABLE
    chop LIST
    chop    Chops off the last character of a string and
            returns the character chopped.  It is much more
            efficient than "s/.$//s" because it neither scans
            nor copies the string.  If VARIABLE is omitted,
            chops $_.  If VARIABLE is a hash, it chops the
            hash's values, but not its keys.
    
            You can actually chop anything that's an lvalue,
            including an assignment.
    
            If you chop a list, each element is chopped.  Only
            the value of the last "chop" is returned.
    
            Note that "chop" returns the last character.  To
            return all but the last character, use "sub-
            str($string, 0, -1)".
    
    
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: "Chop" problems
by Zaxo (Archbishop) on Oct 12, 2002 at 06:04 UTC

    chop modifies its argument and returns the chopped character. Does your program print 'd'?

    I'm assuming the html line breaks are a posting error and not present in your source.

    Don't use $a or $b as a user variable, they are owned by sort.

    After Compline,
    Zaxo

    A reply falls below the community's threshold of quality. You may see it by logging in.
A reply falls below the community's threshold of quality. You may see it by logging in.