the opposite of 'chop'

Discussion in 'Perl Misc' started by Mark Tarver, Nov 24, 2006.

  1. Mark Tarver

    Mark Tarver Guest

    I understand 'chop' grabs the last token of a string. What grabs the
    first?

    Mark
     
    Mark Tarver, Nov 24, 2006
    #1
    1. Advertisements

  2. Mark Tarver

    Paul Lalli Guest

    You understand incorrectly. chop() does not "grab" the last character
    in a string. It removes the last character from the string, and then
    returns whatever that character was. That is, it directly modifies the
    string you pass to it.
    There is no direct functional equivalent for the beginning of the
    string. If you'd like, you can use substr:

    my $first_char = substr($string,0,1, q{});

    Paul Lalli
     
    Paul Lalli, Nov 24, 2006
    #2
    1. Advertisements

  3. Mark Tarver

    Henry Law Guest

    I thought this was a typo until I looked up perlop; I see that q{} is
    synonymous with ''. Is there a particular benefit from using q{}
    rather than '' here? I understand that it's very convenient when
    single-quoting a string that contains a single quote.
     
    Henry Law, Nov 24, 2006
    #3
  4. Mark Tarver

    Mark Tarver Guest

    thanks - new question posted.

    Mark

     
    Mark Tarver, Nov 24, 2006
    #4
  5. Mark Tarver

    Paul Lalli Guest

    Because '' looks far too much like " and that can be confusing to
    people reading the code.

    Paul Lalli
     
    Paul Lalli, Nov 24, 2006
    #5
  6. Mark Tarver

    John Bokma Guest

    or reverse the string, chop it, and reverse it back :)
     
    John Bokma, Nov 24, 2006
    #6
  7. Mark Tarver

    Big and Blue Guest

    Why is there anything there at all?

    my $first_char = substr($string, 0, 1);

    does the job without any confusion.
     
    Big and Blue, Nov 25, 2006
    #7
  8. Mark Tarver

    Ben Morrow Guest

    No, that's not the same as a 'reverse chop'. The version given deletes
    the first char of the string, as well as returning it.

    Ben
     
    Ben Morrow, Nov 25, 2006
    #8
  9. Mark Tarver

    Paul Lalli Guest

    Only if you define "the job" to mean "half of what chop() does", which
    was the exact mistake the OP made when I answered him too.

    Paul Lalli
     
    Paul Lalli, Nov 26, 2006
    #9
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.