_learning perl_, ch15, 14.I.2002, nh OTHER DATA TRANSFORMATION finding a substring ~~~~~~~~~~~~~~~~~~~ if within a bigger string, use `index`: $x = index($string,$substring); | `-> returns index value of place found in string -- at beginning, you get '0'. after 1st ch, '1'. &c. (returns -1 if no match) | `-> can take 3rd parameter -- leftmost limit at which to start searching | `-> find right-most occurrence using `rindex` (also can take 3rd-parameter index, for >= instead of <=) extracting and replacing a substring ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ substr() ------------------------------- - use it if you know where the substring you want is in the string - negative start value counts back from end - omitting length is same as making it a ridiculously huge # - can also go on left side of assignment operator: $hw = "hello world!"; substr($hw,0,5) = "hey"; # $hw is now "hey world!" (length of replacement text doesn't have to be the same) formatting data wiht sprintf() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ sprintf() = printf() except that it returns the formatted data as one string -- "String printf()" $string = sprintf("%5d %8s", $x, $otherstring); advanced sorting ~~~~~~~~~~~~~~~~ `sort` already sorts by ASCII value must compare values numerically, two at a time: sub by_numer { return -1 if ($a < $b); return 0 if ($a == $b); return 1 if ($a > $b); } @list = sort by_number @wronglist; * special operator: 'spaceship operator': <=> sub by_number { $a <=> $b; } can also do: @rightlist = sort { $a <=> $b } @wronglist; spaceship is for numeric; `cmp` is for strings both numeric and non- at the same time: sub mostly_by_number { ($a <=> $b) || ($a cmp $b); } transliteration ~~~~~~~~~~~~~~~ `tr` -- transliterates, instead of just substituting ^^^^ tr/ab/ba/; # just like shell `tr ab ba` syntax: tr/// $_ = "fred and barney"; tr/fb/bf/; # $_ now = "bred and farney" tr/a-z/A-Z/; # $_ now = "BRED AND FARNEY" * if new string is shorter,