How do I go about removing leading and trailing spaces from a text field when passed to a script?
Also, how do I verify that an email address is in the correct format on a form?
s/^\s*\(.+)\s*$/$1/
more efficient suggestion:
my $string = ' Mary had a little lamb. ';
$string =~ s/^\s+//; #remove leading spaces
$string =~ s/\s+$//; #remove trailing spaces
print $string;
use the Email::Valid module to check email addresses
http://search.cpan.org/~rjbs/Email-Valid-0.176/lib/Email/Valid.pm
Oh, I just noticed too, that I accidentally inserted a \ in front of the first paren.
Although, to tell you the truth, I don't know if yours is truely measurably more effecient (unless the string is very long). I feel it's simply more a personal preference (once again, depending on the length of the string, due to the amount of backtracking).
Maybe try a Benchmark test
In this case they are for all practical purposes equal:
use Benchmark qw/timethese cmpthese/;
my $string = " Mary had a little lamb. ";
my $results = timethese(200000,
{
'First' => sub {$string =~ s/^\s*//;$string =~ s/\s*$//;},
'Second' => sub {$string =~ s/^\s*(.+)\s*$/$1/;}
},
);
cmpthese( $results ) ;
output:
Benchmark: timing 200000 iterations of First, Second...
First: 3 wallclock secs ( 2.36 usr + 0.00 sys = 2.36 CPU) @ 84745.76/s (n=200000)
Second: 2 wallclock secs ( 2.58 usr + 0.00 sys = 2.58 CPU) @ 77519.38/s (n=200000)
Rate Second First
Second 77519/s -- -9%
First 84746/s 9% --
I would still recommend the two regexp solution as a force of good habit though.
Thanks for your help, guys. Got it figured out now.
I would still recommend the two regexp solution as a force of good habit though.
You're probably right, but I, myself, will sometimes settle for brevity (as in this case), since most of the perl scripts I have to write have no real need of this type of optimization. They are usually neither runtime sensitive (to a point, of course), nor do they usually have to deal with large blocks of text. ;-)
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.