How to insert text into a string in Perl?

If I had:

$foo= "12."bar bar bar"|three";

how would I insert the text ".." after text 12. in a variable?

+3
source share
3 answers

Perl lets you choose your own quote separators. If you find that you need to use a double quote inside an interpolating string (i.e. "") or a single quote inside a non- interpolating string (i.e. ) '', you can use the quote operator to specify another character that will act as a separator for the string . Separators come in two forms: in square brackets and without fixation. Restrictions in square brackets have different starting and ending symbols: [], {}, (), []and <>. All other characters *are available as non-blocking delimiters.

So your example can be written as

$foo = qq(12."bar bar bar"|three);

"12." (TIMTOWDI). , .

$foo =~ s/^(12[.])/$1../;

^ , () $1, 12 "12", [] . , . , ([]). , . \, , , .

$foo =~ s/^(12\.)/$1../;

- substr. Perl : lvalues. .

substr($foo, 3, 0) = "..";

, "12." , index, , , length, , "12." substr.

Perl script, .

#!/usr/bin/perl

use strict;
use warnings;

my $foo = my $bar = qq(12."bar bar bar"|three); 

$foo =~ s/(12[.])/$1../;

my $i = index($bar, "12.") + length "12.";
substr($bar, $i, 0) = "..";

print "foo is $foo\nbar is $bar\n";

* , (, , , , ),

+17

Perl, :

$foo = "12.\"bar bar bar\"|three";

$foo = '12."bar bar bar"|three';

.

. , . , $var @array . :

$myvar = 123;
$mystring = '"$myvar"';
print $mystring;
> "$myvar"

:

$myvar = 123;
$mystring = "\"$myvar\"";
print $mystring;
> "123"

Quote-like Operators, .

0

$foo = "12.\"bar bar bar\"|three";
$foo =~s/12\./12\.\.\./;
print $foo; # results in 12...\"bar bar bar\"|three"
0
source

Source: https://habr.com/ru/post/1704786/


All Articles