[NBLUG/talk] Another stupid Perl question....
Eric Eisenhart
eric at nblug.org
Tue Jun 7 14:39:15 PDT 2005
On Tue, Jun 07, 2005 at 02:12:02PM -0700, Mark Street wrote:
> Let's say I get a response back from a webserver and I assign that response
> into a variable $res
>
> $res = $ua->request($req1)->as_string;
>
> Now I have everything I want inside of that var $res. I tried to use a
> substring function to try to grok out some values but I am missing
> something...... Tell me please...
>
> $ss = get_ss( "SERVERSESSION=\"", $res );
> ########
> sub get_ss( $$ ) {
> # $_[0] = string to search for, e.g., SERVERSESSION
> # $_[1] = string to search, e.g., $res
>
> return substr( $_[1], index( $_[1], $_[0] ) + length($_[0]), 18 );
> }
Well, first off, you're missing out on some readability.
sub get_ss( $$ ) {
my $sub = shift;
my $str = shift;
return substr ( $str,
index ( $str, $sub ) + length ( $sub ),
18 );
}
Second, you're not checking if $res is set...
Third, you're not checking if the substring is in there -- index will return
a -1 if it's not found, but -1 is a *meaningful value* to the offset of
substr, and -1 plus 15 is (obviously) even more meaningful.
But, fourth and most critical, you're doing it the hard semi-C-style way
instead of the easier Perl way (aka "via a regular expression").
sub get_ss( $$ ) {
my $sub = shift;
my $str = shift;
if ( $str =~ m/ \Q$sub\E (.{18}) /msx ) { # indent regex if wanted
return $1;
} else {
return undef; # or die? do you like exceptions?
}
}
Or, if you really prefer brevity over understandability:
sub get_ss ( $$ ) {
return (($_[1] =~ m/\Q$_[0]\E(.{18)/msx)[0]);
}
--
Eric Eisenhart
NBLUG Co-Founder, Scribe and InstallFest Coordinator
The North Bay Linux Users Group -- http://nblug.org/
eric at nblug.org, IRC: Freiheit at fn AIM: falschfreiheit
More information about the talk
mailing list