Recently, I was asked in an interview question to reverse a string in perl. I wrote the code and they wanted me to give some example strings to test it. I gave them examples like a string with few characters, lot of characters, invalid characters etc etc. But they also asked what is the longest string I will test with. I was not sure what to tell. Hence this question. What is the longest string I can test in a perl code ? What does it depend on ? Memory on the machine ? Is there any limitation from perl stand point ?
While an individual quoted string cannot be longer than 2048 bytes, a string literal of roughly 65535 bytes can be constructed by concatenating strings.
The maximum length of a string literal allowed in Microsoft C is approximately 2,048 bytes.
On a 32 bit system it's around 2 billion or 500 million characters.
To calculate the length of a string in Java, you can use an inbuilt length() method of the Java string class. In Java, strings are objects created using the string class and the length() method is a public member method of this class. So, any variable of type string can access this method using the . (dot) operator.
I was looking to see if I can find any official documentation on the longest string. I found one at http://perltutorial.org talking about Strings:
Perl defines string as a sequence of characters. The shortest string contains no character or null string. The longest string can contain unlimited characters which is only limited to available memory of your computer.
I don't know if this is official enough for you. It'd be nice to see something in the FAQ or Perldoc.
By the way, to officially reverse a string in Perl:
my $rev_string = reverse $string;
This is in the Perl FAQ #4 which has a bunch of string handling stuff in it. The reverse a string question is an old trick interview question to see if someone knows their arcane Perl stuff. Sure almost everyone knows reverse
will reverse an array, but do they also know it will reverse a string? Noobies will work out some sort of complex algorithm and the interviewer will have a reason to feel smug and not hire that person.
Personally, if I was interviewing someone, I asked this question, and someone came up on the spot with an elegant algorithm and showed me how it would work with short, long, and invalid characters, I'd hire them. You can always learn new stupid Perl tricks, but quick-on-your-feet type of thinking is something that's hard to find.
I learned the reverse string trick a long time ago when someone asked me the same question in an interview. I looked it up and found it in the FAQ and realized I did it wrong. I've been using Perl for almost 20 years and I can't think of a time I had ever had to reverse a Perl string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With