Strings
## Learning Objectives
- Master string manipulation
- Use string functions
- Work with Unicode
- Format strings
- Use here-documents
## String Basics
### Single Quotes
```perl
use strict;
use warnings;
my $str = 'Hello, World!';
my $escaped = 'She said \'Hi\''; # Escape single quotes
my $backslash = 'C:\\Program Files'; # Single backslash
```
### Double Quotes
```perl
use strict;
use warnings;
my $name = "Alice";
my $greeting = "Hello, $name!"; # Interpolation
my $calc = "2 + 2 = @{[(2+2)]}"; # Expressions in strings
my $array_ref = [1, 2, 3];
my $text = "Array: @$array_ref"; # Dereference
```
### qq// Operator
```perl
use strict;
use warnings;
# qq{} is double-quoted string
my $text = qq{Hello, $name!};
# Useful for strings with quotes
my $html = qq{Click};
```
## String Functions
### length
```perl
use strict;
use warnings;
my $str = "Hello";
print length($str); # 5
# Unicode length
use encoding 'utf8';
my $unicode = "Hello";
print length($unicode); # May vary with Unicode
```
### substr
```perl
use strict;
use warnings;
my $str = "Hello, World!";
# substr EXPR, OFFSET, LENGTH
my $part = substr($str, 0, 5); # "Hello"
my $part = substr($str, 7); # "World!"
# Replace in place
substr($str, 0, 5) = "Hi"; # "Hi, World!"
```
### index and rindex
```perl
use strict;
use warnings;
my $str = "Hello, World! Hello again.";
my $pos = index($str, "World"); # 7
my $pos = index($str, "Hello"); # 0 (first)
my $pos = rindex($str, "Hello"); # 14 (last)
# With starting position
my $pos = index($str, "o", 5); # 8
```
### lc, uc, lcfirst, ucfirst
```perl
use strict;
use warnings;
my $str = "Hello, World!";
print lc($str); # "hello, world!"
print uc($str); # "HELLO, WORLD!"
print lcfirst($str); # "hello, World!"
print ucfirst($str); # "Hello, World!"
```
### capitalize ( POSIX )
```perl
use strict;
use warnings;
use POSIX qw(toupper tolower);
my $str = "hello";
# Manual capitalize
my $cap = ucfirst(lc($str)); # "Hello"
# Using POSIX
print toupper("a"); # "A"
print tolower("A"); # "a"
```
## String Manipulation
### split
```perl
use strict;
use warnings;
my $line = "apple,banana,cherry";
my @fruits = split /,/, $line; # ("apple", "banana", "cherry")
# With limit
my @parts = split /:/, "a:b:c:d", 2; # ("a", "b:c:d")
# Split on whitespace
my $text = "one two three";
my @words = split /\s+/, $text; # ("one", "two", "three")
```
### join
```perl
use strict;
use warnings;
my @words = ("Hello", "World");
my $sentence = join "-", @words; # "Hello-World"
my $csv = join ",", @fruits;
```
### chomp and chop
```perl
use strict;
use warnings;
# chomp removes trailing newline
my $line = ;
chomp $line; # Removes \n
# chop removes last character
my $str = "Hello";
chop $str; # "Hell"
```
### tr/// (Transliteration)
```perl
use strict;
use warnings;
my $str = "hello";
$str =~ tr/a-z/A-Z/; # "HELLO"
# Count
my $count = ($str =~ tr/a//); # Count 'a's
# Delete
my $clean = $str =~ tr/a-z//cdr; # Delete non-lowercase
```
## sprintf
```perl
use strict;
use warnings;
# sprintf FORMAT, LIST
my $formatted = sprintf("%05d", 42); # "00042"
my $formatted = sprintf("%.2f", 3.14159); # "3.14"
my $formatted = sprintf("%10s", "Hello"); # " Hello"
# Multiple values
my $line = sprintf("%-10s %5d", "Alice", 30);
```
### Format Specifiers
| Specifier | Description |
|-----------|-------------|
| `%d` | Integer |
| `%f` | Float |
| `%s` | String |
| `%x` | Hex |
| `%o` | Octal |
| `%b` | Binary |
### Format Flags
```perl
sprintf("%05d", 42); # "00042" (zero-pad)
sprintf("%-10s", "Hi"); # "Hi " (left-align)
sprintf("%+d", 42); # "+42" (force sign)
sprintf("%.3f", 3.14); # "3.140" (precision)
```
## Here-Documents
### Basic Here-Doc
```perl
use strict;
use warnings;
my $text = <<"END";
This is a here-document.
Multiple lines are supported.
Variables like $name work.
END
print $text;
```
### Single-Quoted Here-Doc
```perl
use strict;
use warnings;
my $text = <<'END';
This is NOT interpolated.
$name stays as literal.
END
print $text;
```
### Here-Doc with Quoted Identifier
```perl
use strict;
use warnings;
# Shell-style (no quotes)
my $sh_text = < apple)
my $result = "apple" cmp "apple"; # 0 (equal)
# For sorting
my @sorted = sort { $a cmp $b } ("banana", "apple", "cherry");
```
## String Templates
### Template with Placeholders
```perl
use strict;
use warnings;
use Template;
my $template = Template->new();
my $vars = { name => "Alice", age => 30 };
$template->process(\ <<'END', $vars);
Name: [% name %]
Age: [% age %]
END
```
## String Performance
### String Concatenation
```perl
use strict;
use warnings;
# Good for few concatenations
my $str = "Hello" . " " . "World";
# For many concatenations, use join
my @parts = ();
for my $i (1 .. 1000) {
push @parts, "Item $i";
}
my $result = join "\n", @parts;
```
### String::XS
```perl
# For performance-critical string operations
use String::XS;
```
## Summary
- Single quotes for literal strings, double quotes interpolate
- `qq{}` is alternative double-quote syntax
- `substr`, `index`, `length` for basic operations
- `split` and `join` for splitting/combining
- `sprintf` for formatted output
- Here-documents for multi-line strings
- Use `utf8` pragma for Unicode
- `tr///` for character transliteration
- `=~` binds regex to string
- `s///` for substitution, `m//` for matching
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →