See substr to access single characters.
But the "usual" way is
for my $c (split //, $string) {
print $c;
}
Update
Alternatively:
while ( $string =~ m/(.)/g ){
print $1;
}
update
made code clearer
| [reply] [d/l] [select] |
c:\@Work\Perl\monks>perl -wMstrict -le
"my $string = 'foobar';
;;
for my $offset (0 .. length($string) - 1) {
printf qq{'%s' }, substr $string, $offset, 1;
}
"
'f' 'o' 'o' 'b' 'a' 'r'
Give a man a fish: <%-(-(-(-<
| [reply] [d/l] [select] |
| [reply] [d/l] |
Sorry for asking such question,as i am new to perl. What i need is ,i have a scalar element $name='krishna'.I need to print only any one of the character in the string like i need only 'i' to be printed.
| [reply] |
c:\@Work\Perl\monks>perl -wMstrict -le
"my $name = 'krishna';
print substr $name, 2, 1;
"
i
See substr.
Give a man a fish: <%-(-(-(-<
| [reply] [d/l] [select] |
... can i only print required characters in a scalar element
Adressing the second half of your question: There are ways to print only specific character that exist in a scalar (without modifying it), yes. What is the actual requirement?
Cheers, Sören
Créateur des bugs mobiles - let loose once, run everywhere.
(hooked on the Perl Programming language)
| [reply] |
Let me try to explain things a bit . . .
As the name sort-of implies, a “scalar” is: “one thing.”1 However, in Perl, one of the “one things” that it can also be is “a reference.” (See the perldocs, e.g. perldsc, perllol, perlref ...)
It is very common in Perl to store references to things in scalar variables ... ordinarily, references to things that are referred-to nowhere else. Hence the common Perl slang terms, “arrayref,” “hashref,” and so on. You see idioms like (emphasis added ...)
foreach @{$somescalar}
... all the time, which is iterating over the probably-anonymous thing (an array, in this case) that $somescalar refers to. The perldsc perldoc topic is a great place to start reading.
HTH ...
- - - - - - - - - -
1 For my purposes here, a string is also “one” thing, in order to say that I’m not [necessarily ...] talking about strings.
| |
| [reply] [d/l] |