Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am stymied by a result I am getting from my perl script. Here are the results:
Line = 'org_name,"My Organization"' Field = 'org_name ' Field Length = 9 Trim Length = 'org_name ' Line ($line) is a string to which I want to compare some key words. Field ($field) is one of the key words. I have placed single quotes ar +ound the value so I can see its length. Field Length ($length) is the result of the Perl length($field) functi +on. Trim Length ($trim_length) is the result of substr ($field, 0, $length +). $field is read from a database table using the @fields = qx{query}; The relationship between @fields and $field comes from a foreach @fiel +d (@fields) loop.
If I write the results of the qx{query} to a file and inspect the contents with vi, each line is the appropriate length (ie, length($field)). Why are $field and trim_length so long? The extra bytes are keeping my compare to $line from finding equality. What can I do to trim the extra bytes from the $field values? Obviously the substr isn't working. Any help greatly appreciated.

Replies are listed 'Best First'.
Re: Extraneous Data in Variable
by matija (Priest) on Apr 03, 2004 at 16:42 UTC
    It is hard to guess if your code really does what you think it does - we only have your word for it. Considering that substr works for a lot of other people, so it is much more likely that the bug is in your code, rather than in substr.

    For instance, you say:
    Field Length ($length) is the result of the Perl length($field) function.
    Trim Length ($trim_length) is the result of substr ($field, 0, $length).
    But that means that if you put the two together, you get:

    substr($field,0,length($field));
    Which means "extract from the string everything between the start of the string and the end of the string, and return it". You get the whole string, naturally.

    And where do the newlines come from, that we see in the value of Field and Trim Length?

    Can you post a short example that demonstrates the problem? Maybe then we can spot your error for you.

Re: Extraneous Data in Variable
by ambrus (Abbot) on Apr 03, 2004 at 19:38 UTC

    Carriage returns?

Re: Extraneous Data in Variable
by ysth (Canon) on Apr 04, 2004 at 11:51 UTC
    Those aren't spaces at the end of Field and Trim Length, those are newline characters. Try:
    use Data::Dumper; $Data::Dumper::Useqq = 1; print Dumper $field;
      I believe you are correct. Is there an available function to strip the carriage return from a string?