substr takes an expression (here $str), an offset (index of starting character) and length. You need to keep in mind that offset is zero based.
In your example, you take the first 3 characters ("Jan"), then concatenate that with the characters at index 4 and 5 (" "), which you strip of the spaces (""), then the characters at index 7,8 ("11").
Perl is an excellent language in that you don't need to "translate" what you want to do with how you need to write it. If what you want is to "strip all whitespace from $str" then simply write
$str =~ s/\s+/g
(the g modifier means the action will be repeated as long as necessary. If your intention is different, a different solution can be used.
Excellent alternative @erezschatz, and good explanation of the original problem, except for when you saythe characters at index 4 and 5 (" ") because the characters at
index 4 and 5 look to me like "8 " as the following demonstrates:
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
#The following is the OP's example (typos $Str corrected to $str)
my $str = "Jan 8 11"; # Jan, 8th 11 o'clock
#print substr($str, 0,3) . substr($str, 4,2)=~s/^\s+// . substr($str, 7,2) . "\n";
#OK. What is the value of substr($str, 4,2) without the substitution?
my $middle_substring = substr($str, 4,2);
say "*****$middle_substring*****"; #Prints *****8 *****! Why?
#Let's print what the middle part of the above gives you.
my $middle_substring_stripped = substr($str, 4,2)=~s/^\s+//;
say "*****$middle_substring_stripped*****"; #$middle_substring_stripped is empty.
#What happened to the 8?
d5e5
Practically a Posting Shark
810 posts since Sep 2009
Reputation Points: 159
Solved Threads: 159