Anfang eines Strings abschneiden
OJ
- perl
0 timothy0 OJ
0 Beate Mielke
Hallo,
ich schreibe gerade ein kleines Perlprogramm (mein erstes).
Dabei habe ich folgendes Problem:
Die Eingabe des Benutzers prüfe ich, ob sie am Anfang oder Ende Leerzeichen enthält.
Ist dies der Fall, will ich diese abschneiden.
Am Ende mach ich das mit dem CHOP-Befehl, aber wie kann ich was vom Anfang eines Strings abschneiden? Gibt es da auch einen Befehl. Habe leider nichts diesbezüglich gefunden.
Ich wäre dankbar für einen Tipp.
Tschüß
OJ
Am Ende mach ich das mit dem CHOP-Befehl, aber wie kann ich was vom Anfang eines Strings abschneiden? Gibt es da auch einen Befehl. Habe leider nichts diesbezüglich gefunden.
Ich wäre dankbar für einen Tipp.
lt. Perl-Cook-Book:
1.14. Trimming Blanks from the Ends of a String
Problem
You have read a string that may have leading or trailing whitespace, and you want to remove it.
Solution
Use a pair of pattern substitutions to get rid of them:
$string =~ s/^\s+//;
$string =~ s/\s+$//;
You can also write a function that returns the new value:
$string = trim($string);
@many = trim(@many);
sub trim {
my @out = @_;
for (@out) {
s/^\s+//;
s/\s+$//;
}
return wantarray ? @out : $out[0];
}
Discussion
This problem has various solutions, but this is the most efficient for the common case.
If you want to remove the last character from the string, use the chop function. Version 5 added chomp, which removes the last character if and only if it is contained in the $/ variable, "\n" by default. These are often used to remove the trailing newline from input:
while(<STDIN>) {
chomp;
print ">$_<\n";
}
Bye
Timothy
Hallo timothy, hallo Beate!
Vielen Dank, bin jetzt einen Schritt weiter.
Ich habe die Lösung aus timothy's "Kochbuch" genommen:
$string =~ s/^\s+// #schneidet Leerzeichen am Anfang weg.
Beates Lösungsvorschlag lieferte mir zunächst immer den Wert 1 zurück:
$string = s/^ *//;
Doch nach kurzer Ratlosigkeit stellte sich herraus, daß nach dem Gleichheitszeichen ein '~' unterschlagen wurde.
$string =~ s/^ *//;
lieferte dann ebenfalls das gewünschte Ergebnis.
Vielen Dank euch beiden,
OJ
Hallo OJ,
ich meine so muesste es gehen:
$string = s/^ *//;
(zwischen dem ^ und dem * ist ein Leerzeichen)
Viele Gruesse
Beate Mielke