Perl FAQ - FAQ (4) - DATA: STRINGS

xiaoxiao2021-03-31  198

How do I validate INPUT? The answer to this question is usually a regular expression, Perhaps with auxiliary logic. See More Specific Questions (Numbers, Email Addresses, etc.) For Details.

How do I unescape a string? It depends just what you mean by `` escape ''.

URL Escapes Are DEALT WITH IN

THELFAQ9 MANPAGE. Shell escapes with the backslash (/) Character Are Removed with:

s ///(.) / $ 1 / g;

Note That this won't expand / n or / t or any other special escapes.

How do I remove consecutive pairs of characters? To turn `` abbcccd '' Into `` Abccd '':

s /( (.) / 1 / $ 1 / g;

How do I expand function calls in a string? This is docutented in

The Perlref MANPAGE. IN General, this is Fraught with Quoting and Readability Problems, But it is possible. To Interpolate A Subroutine Call (in a list) Into a string:

Print "my sub returned @ {[mysub (1, 2, 3)]} That Time./N";

If You Prefer Scalar Context, Similar Chicanery Is Also Useful for Arbitrary Expressions:

Print "That Yields $ {/ ($ N 5)} widgets / n";

See Also `` HOW CAN I Expand Variables in text strings' '' in this section of the faq.

How do i find matching / nesting anything? This isn't Something That Can Be Tackled in One Regular Expression, No Matter How Complicated. To Find Something Between Two Single Characters, A Pattern Like

/ x ([^ x] *) x / will get the intervening bits in $ 1. for multiple one, then Something More Like

.

How do I Reverse A String? USE

Reverse () in a scalar context, as docutented in

REVERSE.

$ REVERSED = Reverse $ String; How do I expand tabs in a string? You can do it the old-fashioned Way:

1 While $ String = ~ S // T / '' X (Length (___ fckpd___5Amp;) * 8 - Length (

How do i validate input?

The answer to this question is usually a regular expression, Perhaps with auxiliary logic. See More Specific Questions (Numbers, Email Addresses, etc.) For Details.

How do i unescape a string?

IT Depends Just What You Mean By `` escape ''. URL Escapes Are Dalt With in The Perlfaq9 ManPage. Shell Escapes with The Backslash (/) Character Are Removed with:

s ///(.) / $ 1 / g;

Note That this won't expand / n or / t or any other special escapes.

How do I Remove Consecutive PAIRS of Characters?

To Turn `` Abbcccd '' Into `` Abccd '':

s /( (.) / 1 / $ 1 / g;

How do I expand function calls in a string?

THIS DOCUMENTED IN The Perlref MANPAGE. IN General, This Is Frauplems, But it is possible. To Interpolate A Subroutine Call (in a list) Into A String:

Print "my sub returned @ {[mysub (1, 2, 3)]} That Time./N";

If You Prefer Scalar Context, Similar Chicanery Is Also Useful for Arbitrary Expressions:

Print "That Yields $ {/ ($ N 5)} widgets / n";

See Also `` HOW CAN I Expand Variables in text strings' '' in this section of the faq.

How do i find matching / nesting anything?

This isn't Sometting That Can Be Tackled in One Regular Expression, No Matter How Complicated. To Find Something Between Two Single Characters, A Pattern Like / X ([^ x] *) X / Will Get The Intervening Bits in $ 1. For Multiple One, Then Something MoreGa/would Be Needed. But None of these Deals with Nested Patterns, NOR CAN THEY. For That You'll Have to Write a Parser.how Do I Reverse A String ?

Use Reverse () in A Scalar Context, As Documented in Reverse.

$ REVERSED = REVERSE $ STRING;

How do I expand tabs in a string?

You can do it the old-fashioned Way:

)% 8) / e;

Or You CAN Just Use The Text :: Tabs Module (Part of The Standard Perl Distribution).

Use text :: tabs;

@expanded_lines = expand (@lines_with_tabs);

How do I Reformat a paragraph?

Use text :: Wrap (Part of the Standard Perl Distribution):

Use text :: wrap;

Print Wrap ("/ t", '', @Paragraphs);

The Paragraphs You Give To Text :: Wrap May Not Contain Embedded Newlines. Text :: Wrap Doesn't Justify The Lines (Flush-Right).

How Can I Access / Change THE FIRST N Letters of A String?

There is, us, us, use substr:

$ first_byte = Substr ($ A, 0, 1);

IF you want to modify part of a string

Substr ($ A, 0, 3) = "Tom";

Althought those with a regexp Kind of Thought Process Will Likely Prefer

$ a = ~ s / ^.../ Tom /;

How do i change the nth ccurrence of something?

You Have to Keep Track. For example, let's say you want to change the fiffurrence of `` Whoever '' OR `` Whome '' Into `` Whosoever '' OR `` Whomsoever ', Case Innsitive.

$ count = 0; s {((whom?) EVER} {

$ count == 5 # is it the 5th?

? "$ {2} soever" # yes, swap

: $ 1 # Renege and Leave it there

} IGEX;

How Can I Count The Number of Occurrence of a Substring Withnin A String?

There Are A Number of Ways, With Want a Count of a Certain Single Character (x) Withnin A String, You Can Use Tr /// Function Like SO:

$ String = "thisxlinexhasxsomexx@xinxit":

$ count = ($ String = ~ TR / X / /);

Print "There is $ count x charcters in the string";

THIS FINE IFE ARE JUST LOOKING for a Single Character. However, if you are trying to count multiple character SUBSTRINGS WITHIN A LARGER STRING, TR /// Won't work. What You can do is warap a while () loop arriles A Global Pattern Match. For Example, Let's Count Negative Integers:

$ String = "-9 55 48 -2 23 -76 4 14 -44";

While ($ String = ~ / - / d / g) {$ COUNT }

Print "There $ count negative number number in the string";

How do i Capitalize All The Words On One Line?

To make the first letter of each word Upper case:

$ line = ~ s // b (/ w) // u $ 1 / g;

This Has The Strange Effect of Turning `` don't do it '' Into `` don't do it ''. Sometimes you might Wang, instead (suggested by brian foy ):

$ String = ~ S / (

(^ / w) #at the beginning of the line

| # or

(/ s / w) #Preceded by Whitespace

)

// u $ 1 / xg;

$ String = ~ / ([/ W '] ) // U / L $ 1 / g;

To make the whole line upper case:

$ line = uc ($ line);

To Force Each Word to Be Lower Case, with the first letter Upper case:

$ line = ~ s / (/ w ) // U / L $ 1 / g;

How can I split a [character] delimited string except when inside [character]? (Comma-separated files) Take the example case of trying to split a string that is comma-separated into its different fields. (We'll pretend you said Comma-Separated, Not Comma-Delimited, Which is Different and Almost Never What You Mean.) You can't use split (/, /) Because You Shouldn't split if the comma is inside quotes. for example, take a data Line Like this:

SAR001, "" "" CIMETRIX, INC "," Bob Smith "," Cam ", N, 8, 1, 0, 7," Error, CORE DUMPED "

Due to the restriction of the quotes, this is a fairly complex problem. Thankfully, we have Jeffrey Friedl, author of a highly recommended book on regular expressions, to handle these for us. He suggests (assuming your string is contained in $ text) :

@new = ();

Push (@new, ___fckpd___19) While $ text = ~ m {

"([^ /" //]*(?://) "//] *) *)",? # groups the phrase inside the quotes

| ([^,] ),?

|,

} gx;

Push (@new, undef) if Substr ($ text, -1, 1) EQ ','

IF you want to represent quotation Marks Inside a quotation-mark-delimited Field, escape the with backslashes (eg, c <`` like / '' this / `` ''). Unescaping the a task addressed earlier in this section.

Alternatively, The Text :: Parsewords Module (Part of The Standard Perl Distribution) Lets you say:

Use text :: parse;

@new = quotewords (",", 0, $ text);

How do i strip blank space from the beginning?

The Simplest Approach, Albeit NOT The Fastest, IS Probably Like this:

$ String = ~ s / ^ / s * (. *?) / s * $ / $ 1 /;

IT Would Be Faster to Do this in Two Steps:

$ String = ~ s / ^ / s //;

$ String = ~ s // s $ //; or more nicely written as:

For ($ String) {

S / ^ / s //;

S // s $ //;

}

How do I extract selected columns from a string?

Use substr () or unpack (), Both Documented In The Perlfunc ManPage.

How do i find the SoundEx Value of A String?

Use the standard text :: SoundEx Module Distributed with perl.

How Can I Expand Variables in text strings?

Let's associum That you have a string like:

$ text = 'this has a $ foo in it and a $ bar';

$ TEXT = ~ S / / $ (/ W ) / $ {$ 1} / g;

Before Version 5 of Perl, this had to be done with a double-evAl subsstitution:

$ text = ~ s / (/ w ) / $ 1 / EEG;

Which is bizarre enough That You'll probably actually need new an eeg instinewards. :-)

See Also `` HOW DO I Expand Function Calls in a string? '' In this section of the faq.

What's WRONG WITH ALWAYS Quoting "$ VARS"?

. - quote forcenessification, coercting number and references Into strings, even you don't want the to be.

IF you get upgrade to write odd things like these:

Print "$ VAR"; # bad

$ new = "$ o"; # bad

Somefunc ("$ VAR"); # bad

You'll be in trouble. Those Should (in 99.8% of the case) be the Simpler and more Direct:

Print $ VAR;

$ new = $ old;

Somefunc ($ VAR);

Otherwise, Besides Slowing You Down, You're Going to Break Code When The Thing In The Scalar Is Actually Neither A String Nor a Number, But A Reference:

FUNC (/ @ array);

Sub func {

MY $ Aref = Shift;

My $ oref = "$ isf"; # wrong

}

You can also get into subtle problems on those few operations in Perl that actually do care about the difference between a string and a number, such as the magical autoincrement operator or the syscall () function.Why do not my <

There Must Be No Space After The << Part.

Check for these Three Things:

.................. ..

转载请注明原文地址:https://www.9cbs.com/read-131013.html

New Post(0)