Perl String Operation
Jump to navigation
Jump to search
A Perl String Operation is a string operation in a Perl Programming Language.
- Context:
- It can be supported by a Perl Pattern Matching Expression.
- Example(s):
s/^([^ ]*) *([^ ]*)/$2 $1/
$string =~ s/(\w+)/\u\L$1/g;
- See: Perl Coding Notes, Perl Regular Expression, Perl Data Structure.
References
2010
- (Melli, 2010) ⇒ Gabor Melli. (2010). “Perl String Operation - Examples."
- Trim Whitespaces
sub trim($) { my $string = shift; $string =~ s/^\s+|\s+$//g ; return $string; }
- Swap first two words
s/^([^ ]+([^ ]+)/$2 $1/; s/^([^ ]*) *([^ ]*)/$2 $1/;
- Extract data from a fixed pattern
if (/Time: (..):(..):(..)/) { $hours = $1 ; $mins = $2 ; $secs = $3 ; }
- Extract all instances of a pattern within a line
s/.*?(\[.+?\])*.*?/$1/g Example: echo "a[b]c[de]f[]g" | perl -ne 's/.*?(\[.+?\])*.*?/$1/g; print' ⇒ [b][de]
- Pattern includes a variable
# note that parentheses can be problematic. print "DEBUG: PROT skip if [$prot2] not in [$prot1] \n" if $debug>1 ; if ($prot1 !~ m/($prot2)/) {
- Capitalize The First Letter
$string = uc($string) ; # capitalize the first letter of each space-separated word. $string =~ s/(\w+)/\u$1/g; # capitalize the first letter of each space-separated word and lower case all others. $string =~ s/(\w+)/\u\L$1/g;
- Count the number of items on a string
$string="x-b c-- de" ; # the number of dashes $countDashes = ($string =~tr/[^\-]//) ; # the number of whitespaced tokens. $countTokens = () = (split(/\s+/,$string) ;
- Extract the text window surrounding an item ;
$string="aa bb cc dd ee ff gg" ; # up to 4 characters before and two characters after $string =~ s/.*(.{0,4}dd.{0,2}).*/$1/ ;
- Convert non-ASCII characters into SGML/HTML/XML-style decimal numeric character references (e.g. Ş becomes Ş)
s/([^\x00-\x7f])/sprintf("&#%d;", ord($1))/ge;'