13

How could I take 8 characters of a string, for example:

If I has like this:

my $word ="take first 8 characters";

How could I print this: take fir?

0

3 Answers 3

32

Use substr.

print substr($word, 0, 8);
9

Use the built in substr function. substr($string, $start, $length)

6

From perlfaq4: How can I access or change N characters of a string?:

You can access the first characters of a string with substr(). To get the first character, for example, start at position 0 and grab the string of length 1.

my $string = "Just another Perl Hacker";
my $first_char = substr( $string, 0, 1 ); # 'J'

(See the rest of the article for guidance on changing part of a string.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.