Perl String Functions
by Geethalakshmi[ Edit ] 2010-09-17 12:27:41
Perl String Functions
chop(LIST)
chop(VARIABLE)
chop VARIABLE
chop
Chops off the last character of a string and returns the character chopped. It's used primarily to remove the newline from the end of an input record, but is much more efficient than `s/\n//' because it neither scans nor copies the string. If VARIABLE is omitted, chops `$_'. Example:
while (<>) {
chop; # avoid \n on last field
@array = split(/:/);
...
}
You can actually chop anything that's an lvalue, including an assignment:
chop($cwd = `pwd`);
chop($answer =
);
If you chop a list, each element is chopped. Only the value of the last chop is returned.
crypt(PLAINTEXT,SALT)
Encrypts a string exactly like the crypt() function in the C library. Useful for checking the password file for lousy passwords. Only the guys wearing white hats should do this.
index(STR,SUBSTR,POSITION)
index(STR,SUBSTR)
Returns the position of the first occurrence of SUBSTR in STR at or after POSITION. If POSITION is omitted, starts searching from the beginning of the string. The return value is based at 0, or whatever you've set the `$[' variable to. If the substring is not found, returns one less than the base, ordinarily -1.
length(EXPR)
length EXPR
length
Returns the length in characters of the value of EXPR. If EXPR is omitted, returns length of `$_'.
rindex(STR,SUBSTR,POSITION)
rindex(STR,SUBSTR)
Works just like index except that it returns the position of the LAST occurrence of SUBSTR in STR. If POSITION is specified, returns the last occurrence at or before that position.
substr(EXPR,OFFSET,LEN)
substr(EXPR,OFFSET)
Extracts a substring out of EXPR and returns it. First character is at offset 0, or whatever you've set `$[' to. If OFFSET is negative, starts that far from the end of the string. If LEN is omitted, returns everything to the end of the string. You can use the substr() function as an lvalue, in which case EXPR must be an lvalue. If you assign something shorter than LEN, the string will shrink, and if you assign something longer than LEN, 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().