PDA

View Full Version : SUBSTR question


Tony Davis
07-18-2005, 04:01 PM
I have a string, M14, sometimes M14A, I want to extract the first position of the string into a variable. I am using the function below. I am using SUBSTR but I do not understand how it works. Can someone please clarify?

$lgroup = substr($prod_category,-1,-3);

or should it be:
$lgroup = substr($prod_category,1,1);


Thanks!
-tdavis

Aradon
07-18-2005, 05:28 PM
http://www.icewalkers.com/Perl/5.8.0/pod/func/substr.html


my $name = 'fred';
substr($name, 4) = 'dy'; # $name is now 'freddy'
my $null = substr $name, 6, 2; # returns '' (no warning)
my $oops = substr $name, 7; # returns undef, with warning
substr($name, 7) = 'gap'; # fatal error


So as you can see with substring it starts at index 0 ('f') and then goes to index 3 ('d').

So in your case you'll probably want to do


$lgroup = substr($prod_category,0,0);
to get the first character. Unless of course you want the LAST character. In which you'll probably want to

$lgroup = substr(reverse $prod_category, 0, 0);

Or something like that :)

Jeff Mott
07-18-2005, 10:40 PM
For those last two examples, I believe you actually need to do this...my $first = substr($prod_category, 0, 1);
my $last = substr($prod_category, -1);

Aradon
07-19-2005, 02:11 PM
ah yes, you are right. typo on my end.

Tony Davis
07-19-2005, 03:30 PM
Yes, I actually tried it both ways.
Got it working! Thanks to both of you for your help!
-tdavis