{
    "mode": "perldoc",
    "parameter": "String",
    "section": "-q",
    "url": "https://www.chedong.com/phpMan.php/perldoc/String/json",
    "generated": "2026-06-15T14:07:05Z",
    "sections": {
        "Found in /usr/share/perl/5.34/pod/perlfaq4.pod": {
            "content": "How can I take a string and turn it into epoch seconds?\nIf it's a regular enough string that it always has the same format, you\ncan split it up and pass the parts to \"timelocal\" in the standard\nTime::Local module. Otherwise, you should look into the Date::Calc,\nDate::Parse, and Date::Manip modules from CPAN.\n\nHow do I unescape a string?\nIt depends just what you mean by \"escape\". URL escapes are dealt with in\nperlfaq9. Shell escapes with the backslash (\"\\\") character are removed\nwith\n\ns/\\\\(.)/$1/g;\n\nThis won't expand \"\\n\" or \"\\t\" or any other special escapes.\n\nHow do I expand function calls in a string?\n(contributed by brian d foy)\n\nThis is documented in perlref, and although it's not the easiest thing\nto read, it does work. In each of these examples, we call the function\ninside the braces used to dereference a reference. If we have more than\none return value, we can construct and dereference an anonymous array.\nIn this case, we call the function in list context.\n\nprint \"The time values are @{ [localtime] }.\\n\";\n\nIf we want to call the function in scalar context, we have to do a bit\nmore work. We can really have any code we like inside the braces, so we\nsimply have to end with the scalar reference, although how you do that\nis up to you, and you can use code inside the braces. Note that the use\nof parens creates a list context, so we need \"scalar\" to force the\nscalar context on the function:\n\nprint \"The time is ${\\(scalar localtime)}.\\n\"\n\nprint \"The time is ${ my $x = localtime; \\$x }.\\n\";\n\nIf your function already returns a reference, you don't need to create\nthe reference yourself.\n\nsub timestamp { my $t = localtime; \\$t }\n\nprint \"The time is ${ timestamp() }.\\n\";\n\nThe \"Interpolation\" module can also do a lot of magic for you. You can\nspecify a variable name, in this case \"E\", to set up a tied hash that\ndoes the interpolation for you. It has several other methods to do this\nas well.\n\nuse Interpolation E => 'eval';\nprint \"The time values are $E{localtime()}.\\n\";\n\nIn most cases, it is probably easier to simply use string concatenation,\nwhich also forces scalar context.\n\nprint \"The time is \" . localtime() . \".\\n\";\n\nHow do I reverse a string?\nUse \"reverse()\" in scalar context, as documented in \"reverse\" in\nperlfunc.\n\nmy $reversed = reverse $string;\n\nHow do I expand tabs in a string?\nYou can do it yourself:\n\n1 while $string =~ s/\\t+/' ' x (length($&) * 8 - length($`) % 8)/e;\n\nOr you can just use the Text::Tabs module (part of the standard Perl\ndistribution).\n\nuse Text::Tabs;\nmy @expandedlines = expand(@lineswithtabs);\n\nHow can I access or change N characters of a string?\nYou can access the first characters of a string with substr(). To get\nthe first character, for example, start at position 0 and grab the\nstring of length 1.\n\nmy $string = \"Just another Perl Hacker\";\nmy $firstchar = substr( $string, 0, 1 );  #  'J'\n\nTo change part of a string, you can use the optional fourth argument\nwhich is the replacement string.\n\nsubstr( $string, 13, 4, \"Perl 5.8.0\" );\n\nYou can also use substr() as an lvalue.\n\nsubstr( $string, 13, 4 ) =  \"Perl 5.8.0\";\n\nHow can I count the number of occurrences of a substring within a string?\nThere are a number of ways, with varying efficiency. If you want a count\nof a certain single character (X) within a string, you can use the\n\"tr///\" function like so:\n\nmy $string = \"ThisXlineXhasXsomeXx'sXinXit\";\nmy $count = ($string =~ tr/X//);\nprint \"There are $count X characters in the string\";\n\nThis is fine if you are just looking for a single character. However, if\nyou are trying to count multiple character substrings within a larger\nstring, \"tr///\" won't work. What you can do is wrap a while() loop\naround a global pattern match. For example, let's count negative\nintegers:\n\nmy $string = \"-9 55 48 -2 23 -76 4 14 -44\";\nmy $count = 0;\nwhile ($string =~ /-\\d+/g) { $count++ }\nprint \"There are $count negative numbers in the string\";\n\nAnother version uses a global match in list context, then assigns the\nresult to a scalar, producing a count of the number of matches.\n\nmy $count = () = $string =~ /-\\d+/g;\n\nHow can I split a [character]-delimited string except when inside [character]?\nSeveral modules can handle this sort of parsing--Text::Balanced,\nText::CSV, Text::CSVXS, and Text::ParseWords, among others.\n\nTake the example case of trying to split a string that is\ncomma-separated into its different fields. You can't use \"split(/,/)\"\nbecause you shouldn't split if the comma is inside quotes. For example,\ntake a data line like this:\n\nSAR001,\"\",\"Cimetrix, Inc\",\"Bob Smith\",\"CAM\",N,8,1,0,7,\"Error, Core Dumped\"\n\nDue to the restriction of the quotes, this is a fairly complex problem.\nThankfully, we have Jeffrey Friedl, author of *Mastering Regular\nExpressions*, to handle these for us. He suggests (assuming your string\nis contained in $text):\n\nmy @new = ();\npush(@new, $+) while $text =~ m{\n\"([^\\\"\\\\]*(?:\\\\.[^\\\"\\\\]*)*)\",? # groups the phrase inside the quotes\n| ([^,]+),?\n| ,\n}gx;\npush(@new, undef) if substr($text,-1,1) eq ',';\n\nIf you want to represent quotation marks inside a\nquotation-mark-delimited field, escape them with backslashes (eg, \"like\n\\\"this\\\"\".\n\nAlternatively, the Text::ParseWords module (part of the standard Perl\ndistribution) lets you say:\n\nuse Text::ParseWords;\n@new = quotewords(\",\", 0, $text);\n\nFor parsing or generating CSV, though, using Text::CSV rather than\nimplementing it yourself is highly recommended; you'll save yourself odd\nbugs popping up later by just using code which has already been tried\nand tested in production for years.\n\nHow do I strip blank space from the beginning/end of a string?\n(contributed by brian d foy)\n\nA substitution can do this for you. For a single line, you want to\nreplace all the leading or trailing whitespace with nothing. You can do\nthat with a pair of substitutions:\n\ns/^\\s+//;\ns/\\s+$//;\n\nYou can also write that as a single substitution, although it turns out\nthe combined statement is slower than the separate ones. That might not\nmatter to you, though:\n\ns/^\\s+|\\s+$//g;\n\nIn this regular expression, the alternation matches either at the\nbeginning or the end of the string since the anchors have a lower\nprecedence than the alternation. With the \"/g\" flag, the substitution\nmakes all possible matches, so it gets both. Remember, the trailing\nnewline matches the \"\\s+\", and the \"$\" anchor can match to the absolute\nend of the string, so the newline disappears too. Just add the newline\nto the output, which has the added benefit of preserving \"blank\"\n(consisting entirely of whitespace) lines which the \"^\\s+\" would remove\nall by itself:\n\nwhile( <> ) {\ns/^\\s+|\\s+$//g;\nprint \"$\\n\";\n}\n\nFor a multi-line string, you can apply the regular expression to each\nlogical line in the string by adding the \"/m\" flag (for \"multi-line\").\nWith the \"/m\" flag, the \"$\" matches *before* an embedded newline, so it\ndoesn't remove it. This pattern still removes the newline at the end of\nthe string:\n\n$string =~ s/^\\s+|\\s+$//gm;\n\nRemember that lines consisting entirely of whitespace will disappear,\nsince the first part of the alternation can match the entire string and\nreplace it with nothing. If you need to keep embedded blank lines, you\nhave to do a little more work. Instead of matching any whitespace (since\nthat includes a newline), just match the other whitespace:\n\n$string =~ s/^[\\t\\f ]+|[\\t\\f ]+$//mg;\n\nHow do I pad a string with blanks or pad a number with zeroes?\nIn the following examples, $padlen is the length to which you wish to\npad the string, $text or $num contains the string to be padded, and\n$padchar contains the padding character. You can use a single character\nstring constant instead of the $padchar variable if you know what it is\nin advance. And in the same way you can use an integer in place of\n$padlen if you know the pad length in advance.\n\nThe simplest method uses the \"sprintf\" function. It can pad on the left\nor right with blanks and on the left with zeroes and it will not\ntruncate the result. The \"pack\" function can only pad strings on the\nright with blanks and it will truncate the result to a maximum length of\n$padlen.\n\n# Left padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%${padlen}s\", $text);\nmy $padded = sprintf(\"%*s\", $padlen, $text);  # same thing\n\n# Right padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%-${padlen}s\", $text);\nmy $padded = sprintf(\"%-*s\", $padlen, $text); # same thing\n\n# Left padding a number with 0 (no truncation):\nmy $padded = sprintf(\"%0${padlen}d\", $num);\nmy $padded = sprintf(\"%0*d\", $padlen, $num); # same thing\n\n# Right padding a string with blanks using pack (will truncate):\nmy $padded = pack(\"A$padlen\",$text);\n\nIf you need to pad with a character other than blank or zero you can use\none of the following methods. They all generate a pad string with the\n\"x\" operator and combine that with $text. These methods do not truncate\n$text.\n\nLeft and right padding with any character, creating a new string:\n\nmy $padded = $padchar x ( $padlen - length( $text ) ) . $text;\nmy $padded = $text . $padchar x ( $padlen - length( $text ) );\n\nLeft and right padding with any character, modifying $text directly:\n\nsubstr( $text, 0, 0 ) = $padchar x ( $padlen - length( $text ) );\n$text .= $padchar x ( $padlen - length( $text ) );\n\nHow do I extract selected columns from a string?\n(contributed by brian d foy)\n\nIf you know the columns that contain the data, you can use \"substr\" to\nextract a single column.\n\nmy $column = substr( $line, $startcolumn, $length );\n\nYou can use \"split\" if the columns are separated by whitespace or some\nother delimiter, as long as whitespace or the delimiter cannot appear as\npart of the data.\n\nmy $line    = ' fred barney   betty   ';\nmy @columns = split /\\s+/, $line;\n# ( '', 'fred', 'barney', 'betty' );\n\nmy $line    = 'fred||barney||betty';\nmy @columns = split /\\|/, $line;\n# ( 'fred', '', 'barney', '', 'betty' );\n\nIf you want to work with comma-separated values, don't do this since\nthat format is a bit more complicated. Use one of the modules that\nhandle that format, such as Text::CSV, Text::CSVXS, or Text::CSVPP.\n\nIf you want to break apart an entire line of fixed columns, you can use\n\"unpack\" with the A (ASCII) format. By using a number after the format\nspecifier, you can denote the column width. See the \"pack\" and \"unpack\"\nentries in perlfunc for more details.\n\nmy @fields = unpack( $line, \"A8 A8 A8 A16 A4\" );\n\nNote that spaces in the format argument to \"unpack\" do not denote\nliteral spaces. If you have space separated data, you may want \"split\"\ninstead.\n\nHow do I find the soundex value of a string?\n(contributed by brian d foy)\n\nYou can use the \"Text::Soundex\" module. If you want to do fuzzy or close\nmatching, you might also try the String::Approx, and Text::Metaphone,\nand Text::DoubleMetaphone modules.\n\nHow can I expand variables in text strings?\n(contributed by brian d foy)\n\nIf you can avoid it, don't, or if you can use a templating system, such\nas Text::Template or Template Toolkit, do that instead. You might even\nbe able to get the job done with \"sprintf\" or \"printf\":\n\nmy $string = sprintf 'Say hello to %s and %s', $foo, $bar;\n\nHowever, for the one-off simple case where I don't want to pull out a\nfull templating system, I'll use a string that has two Perl scalar\nvariables in it. In this example, I want to expand $foo and $bar to\ntheir variable's values:\n\nmy $foo = 'Fred';\nmy $bar = 'Barney';\n$string = 'Say hello to $foo and $bar';\n\nOne way I can do this involves the substitution operator and a double\n\"/e\" flag. The first \"/e\" evaluates $1 on the replacement side and turns\nit into $foo. The second /e starts with $foo and replaces it with its\nvalue. $foo, then, turns into 'Fred', and that's finally what's left in\nthe string:\n\n$string =~ s/(\\$\\w+)/$1/eeg; # 'Say hello to Fred and Barney'\n\nThe \"/e\" will also silently ignore violations of strict, replacing\nundefined variable names with the empty string. Since I'm using the \"/e\"\nflag (twice even!), I have all of the same security problems I have with\n\"eval\" in its string form. If there's something odd in $foo, perhaps\nsomething like \"@{[ system \"rm -rf /\" ]}\", then I could get myself in\ntrouble.\n\nTo get around the security problem, I could also pull the values from a\nhash instead of evaluating variable names. Using a single \"/e\", I can\ncheck the hash to ensure the value exists, and if it doesn't, I can\nreplace the missing value with a marker, in this case \"???\" to signal\nthat I missed something:\n\nmy $string = 'This has $foo and $bar';\n\nmy %Replacements = (\nfoo  => 'Fred',\n);\n\n# $string =~ s/\\$(\\w+)/$Replacements{$1}/g;\n$string =~ s/\\$(\\w+)/\nexists $Replacements{$1} ? $Replacements{$1} : '???'\n/eg;\n\nprint $string;\n\nDoes Perl have anything like Ruby's #{} or Python's f string?\nUnlike the others, Perl allows you to embed a variable naked in a double\nquoted string, e.g. \"variable $variable\". When there isn't whitespace or\nother non-word characters following the variable name, you can add\nbraces (e.g. \"foo ${foo}bar\") to ensure correct parsing.\n\nAn array can also be embedded directly in a string, and will be expanded\nby default with spaces between the elements. The default LISTSEPARATOR\ncan be changed by assigning a different string to the special variable\n$\", such as \"local $\" = ', ';\".\n\nPerl also supports references within a string providing the equivalent\nof the features in the other two languages.\n\n\"${\\ ... }\" embedded within a string will work for most simple\nstatements such as an object->method call. More complex code can be\nwrapped in a do block \"${\\ do{...} }\".\n\nWhen you want a list to be expanded per $\", use \"@{[ ... ]}\".\n\nuse Time::Piece;\nuse Time::Seconds;\nmy $scalar = 'STRING';\nmy @array = ( 'zorro', 'a', 1, 'B', 3 );\n\n# Print the current date and time and then Tommorrow\nmy $t = Time::Piece->new;\nsay \"Now is: ${\\ $t->cdate() }\";\nsay \"Tomorrow: ${\\ do{ my $T=Time::Piece->new + ONEDAY ; $T->fullday }}\";\n\n# some variables in strings\nsay \"This is some scalar I have $scalar, this is an array @array.\";\nsay \"You can also write it like this ${scalar} @{array}.\";\n\n# Change the $LISTSEPARATOR\nlocal $\" = ':';\nsay \"Set \\$\\\" to delimit with ':' and sort the Array @{[ sort @array ]}\";\n\nYou may also want to look at the module Quote::Code, and templating\ntools such as Template::Toolkit and Mojo::Template.\n\nSee also: \"How can I expand variables in text strings?\" and \"How do I\nexpand function calls in a string?\" in this FAQ.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq5.pod": {
            "content": "How can I open a filehandle to a string?\n(contributed by Peter J. Holzer, hjp-usenet2@hjp.at)\n\nSince Perl 5.8.0 a file handle referring to a string can be created by\ncalling open with a reference to that string instead of the filename.\nThis file handle can then be used to read from or write to the string:\n\nopen(my $fh, '>', \\$string) or die \"Could not open string for writing\";\nprint $fh \"foo\\n\";\nprint $fh \"bar\\n\";    # $string now contains \"foo\\nbar\\n\"\n\nopen(my $fh, '<', \\$string) or die \"Could not open string for reading\";\nmy $x = <$fh>;    # $x now contains \"foo\\n\"\n\nWith older versions of Perl, the IO::String module provides similar\nfunctionality.\n\nHow can I write() into a string?\n(contributed by brian d foy)\n\nIf you want to \"write\" into a string, you just have to <open> a\nfilehandle to a string, which Perl has been able to do since Perl 5.6:\n\nopen FH, '>', \\my $string;\nwrite( FH );\n\nSince you want to be a good programmer, you probably want to use a\nlexical filehandle, even though formats are designed to work with\nbareword filehandles since the default format names take the filehandle\nname. However, you can control this with some Perl special\nper-filehandle variables: $^, which names the top-of-page format, and $~\nwhich shows the line format. You have to change the default filehandle\nto set these variables:\n\nopen my($fh), '>', \\my $string;\n\n{ # set per-filehandle variables\nmy $oldfh = select( $fh );\n$~ = 'ANIMAL';\n$^ = 'ANIMALTOP';\nselect( $oldfh );\n}\n\nformat ANIMALTOP =\nID  Type    Name\n.\n\nformat ANIMAL =\n@##   @<<<    @<<<<<<<<<<<<<<\n$id,  $type,  $name\n.\n\nAlthough write can work with lexical or package variables, whatever\nvariables you use have to scope in the format. That most likely means\nyou'll want to localize some package variables:\n\n{\nlocal( $id, $type, $name ) = qw( 12 cat Buster );\nwrite( $fh );\n}\n\nprint $string;\n\nThere are also some tricks that you can play with \"formline\" and the\naccumulator variable $^A, but you lose a lot of the value of formats\nsince \"formline\" won't handle paging and so on. You end up\nreimplementing formats when you use them.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq6.pod": {
            "content": "How can I match strings with multibyte characters?\nStarting from Perl 5.6 Perl has had some level of multibyte character\nsupport. Perl 5.8 or later is recommended. Supported multibyte character\nrepertoires include Unicode, and legacy encodings through the Encode\nmodule. See perluniintro, perlunicode, and Encode.\n\nIf you are stuck with older Perls, you can do Unicode with the\nUnicode::String module, and character conversions using the\nUnicode::Map8 and Unicode::Map modules. If you are using Japanese\nencodings, you might try using the jperl 5.00503.\n\nFinally, the following set of approaches was offered by Jeffrey Friedl,\nwhose article in issue #5 of The Perl Journal talks about this very\nmatter.\n\nLet's suppose you have some weird Martian encoding where pairs of ASCII\nuppercase letters encode single Martian letters (i.e. the two bytes \"CV\"\nmake a single Martian letter, as do the two bytes \"SG\", \"VS\", \"XX\",\netc.). Other bytes represent single characters, just like ASCII.\n\nSo, the string of Martian \"I am CVSGXX!\" uses 12 bytes to encode the\nnine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.\n\nNow, say you want to search for the single character \"/GX/\". Perl\ndoesn't know about Martian, so it'll find the two bytes \"GX\" in the \"I\nam CVSGXX!\" string, even though that character isn't there: it just\nlooks like it is because \"SG\" is next to \"XX\", but there's no real \"GX\".\nThis is a big problem.\n\nHere are a few ways, all painful, to deal with it:\n\n# Make sure adjacent \"martian\" bytes are no longer adjacent.\n$martian =~ s/([A-Z][A-Z])/ $1 /g;\n\nprint \"found GX!\\n\" if $martian =~ /GX/;\n\nOr like this:\n\nmy @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;\n# above is conceptually similar to:     my @chars = $text =~ m/(.)/g;\n#\nforeach my $char (@chars) {\nprint \"found GX!\\n\", last if $char eq 'GX';\n}\n\nOr like this:\n\nwhile ($martian =~ m/\\G([A-Z][A-Z]|.)/gs) {  # \\G probably unneeded\nif ($1 eq 'GX') {\nprint \"found GX!\\n\";\nlast;\n}\n}\n\nHere's another, slightly less painful, way to do it from Benjamin\nGoldberg, who uses a zero-width negative look-behind assertion.\n\nprint \"found GX!\\n\" if    $martian =~ m/\n(?<![A-Z])\n(?:[A-Z][A-Z])*?\nGX\n/x;\n\nThis succeeds if the \"martian\" character GX is in the string, and fails\notherwise. If you don't like using (?<!), a zero-width negative\nlook-behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).\n\nIt does have the drawback of putting the wrong thing in $-[0] and $+[0],\nbut this usually can be worked around.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq7.pod": {
            "content": "Do I always/never have to quote my strings or use semicolons and commas?\nNormally, a bareword doesn't need to be quoted, but in most cases\nprobably should be (and must be under \"use strict\"). But a hash key\nconsisting of a simple word and the left-hand operand to the \"=>\"\noperator both count as though they were quoted:\n\nThis                    is like this\n------------            ---------------\n$foo{line}              $foo{'line'}\nbar => stuff            'bar' => stuff\n\nThe final semicolon in a block is optional, as is the final comma in a\nlist. Good style (see perlstyle) says to put them in except for\none-liners:\n\nif ($whoops) { exit 1 }\nmy @nums = (1, 2, 3);\n\nif ($whoops) {\nexit 1;\n}\n\nmy @lines = (\n\"There Beren came from mountains cold\",\n\"And lost he wandered under leaves\",\n);\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq9.pod": {
            "content": "How do I remove HTML from a string?\nUse HTML::Strip, or HTML::FormatText which not only removes HTML but\nalso attempts to do a little simple formatting of the resulting plain\ntext.\n\nHow do I decode a MIME/BASE64 string?\nThe MIME::Base64 package handles this as well as the MIME/QP encoding.\nDecoding base 64 becomes as simple as:\n\nuse MIME::Base64;\nmy $decoded = decodebase64($encoded);\n\nThe Email::MIME module can decode base 64-encoded email message parts\ntransparently so the developer doesn't need to worry about it.\n",
            "subsections": []
        }
    },
    "flags": [],
    "examples": [],
    "see_also": []
}