-2

Okay, I have a problem that is driving me nuts. I'm trying to extract a substring with regex using:

($var) = $data =~ m/regex/;

It's working, but the "string" that's returned isn't quite the same as the real substr. Printing the string looks like the real substr, but checking with an if ($var eq "substr") doesn't return true. I've also noticed that when I try to add something to the end of it with $var .= ".."; I get (if $var is "hello") "..llo".

What is this returning?

I'm running this in Linux if that makes a difference. I wouldn't think it would, but this same code works in Windows for me.

Here's an example of the code:

$datatxt contains
.. 
udir=/home/me/ 
..

use File::Read;
my $data = read_file( {skip_comments => 1}, $datatxt);

($udir) = $data =~ m/udir=(.*)/;
print $udir; #prints /home/me/
print ".".$udir."."; #prints ..home/me/
if ($udir ne "/home/me/") {
   print "not equal"; #prints...
} 
3
  • Do you have any groups in your regex?
    – Cameron
    Apr 24, 2012 at 23:00
  • 6
    You have a \r in the mix somewhere that is causing it. ( do print "hello\r..\n"; and see the result). Windows and *nix use different EOL - specifically, *nix doesn't use \r. If you post an actual example we might be able to offer additional insight. Apr 24, 2012 at 23:02
  • ohh that makes a lot of sense. I copied the data file that's being read from my windows partition. Thanks a lot. Apr 24, 2012 at 23:35

2 Answers 2

2

The string ends with a carriage return.

print "hello\r..\n";   # Looks like "..llo"

Useful in these situations:

use Data::Dumper;
local $Data::Dumper::Useqq = 1;
print(Dumper($str));

Probably the best solution is change

chomp;

to

s/\s+\z//;

It trims all trailing whitespace instead of just the trailing line feed.

1

You'll need to provide specific code. I tried with this code:

#!/usr/bin/perl

$_ = <>;
if (($a) = $_ =~ m/(hello)/) {
    print "it is equal\n" if ($a eq "hello");
    $a .= "..";
    print "$a\n";
} else { 
    print "unmatched\n";
}  

which should reproduce your problem, and the match works. I'm running linux, with perl v5.14.2. On input "hello world", the output is:

it is equal
hello..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.