String

Strings are a sequence of zero or more characters. Perl has many ways of quoting strings, and strings not quoted with single-quote (apostrophe) can contain variables which are replaced dynamically in the string value.

$s = "Hello, World\n";  # Variables and \n replaced
$s = 'webmaster@domain.com'; # No variables replaced, \n would be a literal
$s = "Hello $name"; # With variable
$s = `commmand parameters`; # Executes command in shell, returns STDOUT result
$s = $string1 . $string2; # concatenation
 
##### Basic Operations #####
 
$num_chars = length($string);
$cde = substr("abcdef",2,3); # returns index 2 (3rd char) for 3 chars "cde"
 
@words = split($string); # Splits into multi-space delimited words
@parts = split(/\t/, $string); # Splits at tab character
$s = join("\t",@parts); # Returns each element glued together with tab chars
 
$s = lc($name); # Returns string with all letters in lower case
$s = uc($name); # Returns string with all letters in upper case
$s = chr(56); # Returns 56th ASCII character ("A");
$n = ord('A'); # Returns 56, the ordinal postion of 'A' in the ASCII sequence
$n = index($name,' '); # Returns char index (zero is first) of a space, -1 if not found.

Regular Expression extend the power of processing and parsing strings.

Formating

The sprintf and printf functions are taken mostly from C

$s = sprintf("Int=%d, String=%s", 1, $name);
printf "Int=%d, String=%s", 1, $name;

See the sprintf man page for more specifics.

 
programming/perl/strings.txt · Last modified: 2005/07/18 17:20 by allen