1

A Perl file I'm using contains many instances of s~. I'm not familiar with Perl and am having a hard time finding info on it. I know it's related to a search and replace string. What does s~ do exactly?

Example:

s~ (Text)~ <a href="../images/text.pdf" target="_top">$1</a>~ig if /<p/;
nCardot
  • 5,992
  • 6
  • 47
  • 83
  • 1
    Added links (to the duplicate closure) that tightly relate to this question – zdim Jan 05 '22 at 19:57
  • 1
    I don’t think this should be marked as a dupe. Those other questions pre-suppose you know what this operator is doing. This question is basically “what is this?”, and it’s a fair question for someone who doesn’t know what it’s called and therefore how to look it up. – jimtut Jan 06 '22 at 04:57

1 Answers1

6

The s is the substitution operator. It's used like $str =~ s/this/that/ to change an occurrence of "this" to "that" in $str.

While / is the most common delimiter, s uses whatever non-whitespace character immediately follows to set the delimiter to use in the rest of the expression. (This is true of many other operators, such as m, q, etc., as well.)

This example says to replace the text (Text) with an HTML anchor element, using the i and g flags.

The reason to use ~ rather than the conventional / is to avoid the need to escape the / in the replacement text, like

s/ (Text)/ <a href="..\/images\/text.pdf" target="_top">$1<\/a>/ig if /<p/;

More details can be found by running perldoc -f s.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
chepner
  • 497,756
  • 71
  • 530
  • 681