develooper Front page | perl.beginners | Postings from August 2009

Re: two questions

Thread Previous
From:
Uri Guttman
Date:
August 4, 2009 23:07
Subject:
Re: two questions
Message ID:
87my6e7q05.fsf@quad.sysarch.com
>>>>> "sa" == sys adm <sysadm@computermail.net> writes:

  sa> 1. why perl doesn't have a built-in strip() function? each time I
  sa> need to say $var =~ s/^\s+|\s+//g to strip the blank space before
  sa> and after the variable, specially if this is a CGI var.

because it is so easy to write a strip thing with regexes. and the best
way to write that is:

	$var =~ s/^\s+// ;
	$var =~ s/\s+$// ;

and you forgot the $ anchor.

  sa> 2. what's the standard module or method to generate a random string, for example the string will be used as part of url.

there is no standard module for that. there may be some that do it but
again it is trivial to write.

here is a set of code to generate all sorts of random stuff. it comes
from my Sort::Maker module's t/common.pm file. use it if you want.

my @alpha_digit = ( 'a' .. 'z', 'A' .. 'Z', '0' .. '9' ) ;
my @alpha = ( 'a' .. 'z', 'A' .. 'Z' ) ;
my @bytes = ( "\x00" .. "\xff" ) ;

sub rand_token {

	rand_string( \@alpha_digit, @_ ) ;
}

sub rand_alpha {

	rand_string( \@alpha, @_ ) ;
}

sub rand_bytes {

	rand_string( \@bytes, @_ ) ;
}

sub rand_string {

	my( $char_set, $min_len, $max_len ) = @_ ;

	$min_len ||= 8 ;
	$max_len ||= $min_len ;

	my $length = $min_len + int rand( $max_len - $min_len + 1 ) ;

	return join '', map $char_set->[rand @{$char_set}], 1 .. $length ;
}

sub rand_number {

	my( $lo_range, $hi_range ) = @_ ;

	( $lo_range, $hi_range ) = ( 0, $lo_range ) unless $hi_range ;

	my $range = $hi_range - $lo_range ;

	return rand( $range ) + $lo_range ;
}

sub rand_choice {

	return @_[rand @_] ;
}


uri

-- 
Uri Guttman  ------  uri@stemsystems.com  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
--------- Free Perl Training --- http://perlhunter.com/college.html ---------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About