Funzione substr()
in Perl
Nel linguaggio di programmazione Perl ci sono built-in funzione di substr()
.
Questa funzione viene utilizzata quando si lavora con le stringhe.
Con questa funzione è possibile ottenere una parte di una stringa, o sostituire una parte di una stringa con un'altra stringa.
Ecco un esempio di ricezione della stringa:
▶ Run
my $str = 'Hello, world!';
print "'" . substr($str, 7, 5) . "'";
Questo programma visualizzerà il testo 'world'
. La chiamata di funzione substr($str, 7, 5)
dice che
hanno bisogno di uscire dal comando $str
cinque caratteri a partire dalla settima posizione. Per questo utilizzo
il valore $str
non cambia.
Quando si utilizza la funzione substr()
con quattro argomenti si modifica il valore di una variabile.
Ecco un esempio di utilizzo substr()
per la sostituzione:
▶ Run
my $str = 'Hello, world!';
print "'" . substr($str, 7, 5, 'you') . "'\n";
print $str;
Il valore restituito quando viene chiamato substr($str, 7, 5, 'you')
è esattamente lo stesso come e quando si chiama substr($str, 7, 5)
,
ma la sfida con quattro argomenti ancora e ha cambiato il valore di una variabile. La parola world
è stato sostituito da you
. Siete pregati di
notare che la sostituzione è stata completata con successo anche nonostante il fatto che l'originale parola e in una nuova parola di varie quantità
lettere.
Argomenti
my $str1 = substr($str, $offset);
my $str2 = substr($str, $offset, $length);
my $str3 = substr($str, $offset, $replacement);
Funzioni substr()
, è necessario specificare due, tre o quattro argomenti.
Nel caso in cui se si tenta di utilizzare la funzione di substr()
senza argomenti, o con uno
un argomento, quello è un errore:
Not enough arguments for substr at script.pl line 3, near "substr()"
Execution of script.pl aborted due to compilation errors.
Quando si utilizzano due argomenti substr($str, $offset)
la funzione restituisce
tutti i caratteri dalla stringa $str
a partire con il carattere in posizione $offset
e fino alla fine della riga.
Quando si utilizza tre argomenti substr($str, $offset, $length)
la funzione restituisce
$length
caratteri da una stringa $str
iniziano con il carattere in posizione $offset
.
Quando si utilizza substr()
con due o tre argomenti, il valore di stringa
non cambia.
Quando si utilizza quattro argomenti substr($str, $offset, $replacement)
funzione
restituisce lo stesso che nel caso di tre argomenti, ma ancora di più
sostituisce l'originale linea il valore ottenuto sulla $replacement
.
Il valore restituito
Funzione substr()
può rimborsare o undef
, o una stringa.
undef
restituito nel caso in cui se si tenta di entrare in possesso di un elemento di comando
per l'indice che più di lunghezza della stringa. Ecco un esempio di un programma che restituisce undef
:
▶ Run
use Data::Dumper;
my $str = 'Hello, world!';
my $str1 = substr($str, 10000);
warn Dumper $str1;
Nel caso, se nel codice del programma sarebbe use warnings;
, il programma sarebbe ancora
inoltre ha lo schermo un avviso:
substr outside of string at script.pl line 8.
Valori negativi $offset
Funzioni substr()
consente di specificare un valore negativo per il secondo argomento.
Programma di esempio:
▶ Run
my $str = 'Hello, world!';
print substr($str, -3);
Sullo schermo viene visualizzato il testo ld!
— questi sono gli ultimi tre caratteri da una stringa Hello, world!
.
Negativo secondo argomento indica che la posizione è considerato dalla fine della stringa.
Registrazione substr($str, -3)
perfettamente simile substr($str, -3, 3)
.
Valori negativi $length
Il valore del terzo argomento può essere negativo. Ecco un esempio di lavoro:
▶ Run
use feature qw(say);
my $str = 'Hello, world!';
say substr($str, 7, -1);
say substr($str, 7, -2);
say substr($str, 7, -3);
La documentazione ufficiale di
Ecco l'output del comando perldoc -f substr
:
substr EXPR,OFFSET,LENGTH,REPLACEMENT
substr EXPR,OFFSET,LENGTH
substr EXPR,OFFSET
Extracts a substring out of EXPR and returns it. First character
is at offset zero. If OFFSET is negative, starts that far back
from the end of the string. If LENGTH is omitted, returns
everything through the end of the string. If LENGTH is negative,
leaves that many characters off the end of the string.
my $s = "The black cat climbed the green tree";
my $color = substr $s, 4, 5; # black
my $middle = substr $s, 4, -11; # black cat climbed the
my $end = substr $s, 14; # climbed the green tree
my $tail = substr $s, -4; # tree
my $z = substr $s, -4, 2; # tr
You can use the "substr" function as an lvalue, in which case
EXPR must itself be an lvalue. If you assign something shorter
than LENGTH, the string will shrink, and if you assign something
longer than LENGTH, the string will grow to accommodate it. To
keep the string the same length, you may need to pad or chop
your value using "sprintf".
If OFFSET and LENGTH specify a substring that is partly outside
the string, only the part within the string is returned. If the
substring is beyond either end of the string, "substr" returns
the undefined value and produces a warning. When used as an
lvalue, specifying a substring that is entirely outside the
string raises an exception. Here's an example showing the
behavior for boundary cases:
my $name = 'fred';
substr($name, 4) = 'dy'; # $name is now 'freddy'
my $null = substr $name, 6, 2; # returns "" (no warning)
my $oops = substr $name, 7; # returns undef, with warning
substr($name, 7) = 'gap'; # raises an exception
An alternative to using "substr" as an lvalue is to specify the
replacement string as the 4th argument. This allows you to
replace parts of the EXPR and return what was there before in
one operation, just as you can with "splice".
my $s = "The black cat climbed the green tree";
my $z = substr $s, 14, 7, "jumped from"; # climbed
# $s is now "The black cat jumped from the green tree"
Note that the lvalue returned by the three-argument version of
"substr" acts as a 'magic bullet'; each time it is assigned to,
it remembers which part of the original string is being
modified; for example:
my $x = '1234';
for (substr($x,1,2)) {
$_ = 'a'; print $x,"\n"; # prints 1a4
$_ = 'xyz'; print $x,"\n"; # prints 1xyz4
$x = '56789';
$_ = 'pq'; print $x,"\n"; # prints 5pq9
}
With negative offsets, it remembers its position from the end of
the string when the target string is modified:
my $x = '1234';
for (substr($x, -3, 2)) {
$_ = 'a'; print $x,"\n"; # prints 1a4, as above
$x = 'abcdefg';
print $_,"\n"; # prints f
}
Prior to Perl version 5.10, the result of using an lvalue
multiple times was unspecified. Prior to 5.16, the result with
negative offsets was unspecified.
Temi correlati
Altri articoli
Some parts of this page were machine translated.
Powered by Yandex.Translate
http://translate.yandex.com/