Author Topic: Slight puzzle for the Perl experts  (Read 637 times)

Slight puzzle for the Perl experts
« on: 24 May, 2012, 04:54:24 pm »
I should probably ask this in Perl Monks, but I'd probably be laughed out of the place, so I thought I'd ask on here first. ;D

I've got a simple function to strip any whitespace off of the end of a line:

Code: [Select]
sub rtrim
{
$_[0]=~s/\s+$//;
return $_[0];
}

If I call if like this:

Code: [Select]
@a=("abc","def","ghi");

foreach $string (@a)
{
print (rtrim $string)."\r\n";
}

I get

abcdefghi

... which isn't what I expect.

If I call it like this:

Code: [Select]
@a=("abc","def","ghi");

foreach $string (@a)
{
print rtrim $string;
print "\r\n";
}

It chucks out

abc
def
ghi


Which is what I expected in the first case.  Does anyone understand why it works like this?  I was expecting that putting the brackets around the rtrim $string bit would isolate the "\r\n" from being trimmed off, but it doesn't seem to.  I'm sure I'm missing something obvious here, but I'm not sure what!
Actually, it is rocket science.
 

Re: Slight puzzle for the Perl experts
« Reply #1 on: 24 May, 2012, 05:10:01 pm »
perl -w gives "Useless use of concatenation (.) or string in void context"

From man perlfunc:

       Any function in the list below may be used either with or without
       parentheses around its arguments.  (The syntax descriptions omit the
       parentheses.)  If you use the parentheses, the simple (but occasionally
       surprising) rule is this: It looks like a function, therefore it is a
       function, and precedence doesn't matter.  Otherwise it's a list
       operator or unary operator, and precedence does matter.  And whitespace
       between the function and left parenthesis doesn't count--so you need to
       be careful sometimes:

           print 1+2+4;        # Prints 7.
           print(1+2) + 4;     # Prints 3.
           print (1+2)+4;      # Also prints 3!
           print +(1+2)+4;     # Prints 7.
           print ((1+2)+4);    # Prints 7.

so you want:

   print ((rtrim $string)."\r\n")

Or use python ;)

Re: Slight puzzle for the Perl experts
« Reply #2 on: 24 May, 2012, 05:13:00 pm »
Doh!  I should have used it with "-w", and then would have had something useful to look up.

Slightly odd behaviour, but I have a better grasp on what it's doing now.  Cheers. :thumbsup:
Actually, it is rocket science.