Iam new to Perl Script, am writing a perl script to read a
configuration file and take some actions accordingly. I read each line
of file, split the line in to variables and compare against the
predefined tokens. Comparison fails if variable in file has some
spaces around it.
Eg: Line read from file
Jhon: jack:hill;
spilt(/:/);
if("jack" eq "$_[1])
#Above comparison fails as $_[1] value is " jack"
Please let me know a solution to compare string variables ignoring
spaces around the variables.
Thanks,
-Mushtaq Khan
Fist of all, please don't use split in void or scalar context. It's
considered confusing and is deprecated.
The easiest solution is to just remove them during the splitting.
Something like this:
my @cols = split /\s?:\s?/;
if ($cols[1] eq "jack") {
...
}
Assuming there are no spaces at the start or end of the line, obviously.
Regards,
Leon Timmermans
Thanks, Leon for replying. It's working fine.
See 'perldoc -q sapce':
How do I strip blank space from the beginning/end of a string?
jue
Maybe you could use a regular expression:
if ($_[1] =~ /^\s*jack\s*$/) {
print "It's Jack all right\n";
}
If you must compare with a string contained in a variable, use the \Q
and \E qualifiers:
if ($_[1] =~ /^\s*\Q$name\E\s*$/) {
print "It's $name all right\n";
}
Oh ... TMTOWTDI:
split(/\s*:\s*/);
will take care of the colon as well as surrounding white space.
Then you can just use simple string comparisons with "eq" and "ne".
HTH,
Josef
--
These are my personal views and not those of Fujitsu Siemens Computers!
Josef Möllers (Pinguinpfleger bei FSC)
If failure had no penalty success would not be a prize (T. Pratchett)
Company Details: http://www.fujitsu-siemens.com/imprint.html
LT> Fist of all, please don't use split in void or scalar context. It's
LT> considered confusing and is deprecated.
Why is split in scalar context considered confusing and deprecated? It
seems like a decent way to count the tokens in a word:
my $token_count = split ' ', $data;
You can do something similar with m/(\S+)/g I guess but it gets more
complicated when a token is not as easy to define as the token
separator sequence.
Ted
> spilt(/:/);
> if("jack" eq "$_[1])
Please post real Perl code.
--
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"
You can use the match operator, like this:
if ($_[1] =~ /jack/i) { do_something(); }
CC
Just strip the leading and trailing white space, or all white space, and
then compare.
--
Tim Greer, CEO/Founder/CTO, BurlyHost.com, Inc.
Shared Hosting, Reseller Hosting, Dedicated & Semi-Dedicated servers
and Custom Hosting. 24/7 support, 30 day guarantee, secure servers.
Industry's most experienced staff! -- Web Hosting With Muscle!
You may treat spaces around separator (":") as part of separator.
spilt(/ *: */);
--
[pl>en Andrew] Andrzej Adam Filip : an...@onet.eu : an...@xl.wp.pl
I wasn't kissing her, I was whispering in her mouth.
-- Chico Marx
Because it clobbers up @_.
Regards,
Leon Timmermans