|
google site
|
|||||||
| Forums | Register | Blog | Man Pages | Forum Rules | Links | Albums | FAQ | Users | Calendar | Search | Today's Posts | Mark Forums Read |
| Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here. |
![]() |
|
|
Search this Thread |
|
#1
|
|||
|
|||
|
Perl: Extracting a char from a string.
I want to extract a character from a string. For a C/C++ programmer like me, this would seem to be the most logical and reasonable way--but it doesn't work: Code:
$s = "abcdefg"; $c = $s[2]; This way is documented and it works, but it seems clumsy. Is there any simpler way to grab one character out of a string? Code:
$s = "abcdefg"; $c = substr($s, 2, 1); |
| Sponsored Links | ||
|
|
|
#2
|
||||
|
||||
|
In Perl, strings aren't character arrays like in C (C++ btw has a separate String class too) and can't be manipulated by character. One other way would be to use Code:
$c=((split //, $s)[2]); |
|
#3
|
|||
|
|||
|
Thanks, pludi. Though that one looks nearly as clumsy. And looking at it makes me fear perl would convert the whole string to an integer array before plucking one character out.
It's surprising that perl can be so remarkably terse in many ways, but clumsy in at least this one. |
|
#4
|
||||
|
||||
|
are you sure you always want the character at second position in the string? a more perlish way is to write a regex and use the m operator to extract the character(s) you want. but yes depends on your requirement what exactly you are trying to achieve
|
|
#5
|
|||
|
|||
|
This is a representative sample of what I'm doing: Code:
my $chars = "!#&'()*+.:=@[]^_`{|}~";
for (my $i = 0; $i < $char_count; $i++) {
printf("\"" . substr($chars,$i,1) . " some other text %d, %d\",\n", $a, $b);
# ...
} |
|
#6
|
||||
|
||||
|
Ah, a nice example for TMTOWTDI: Code:
my $chars = "!#&'()*+.:=@[]^_`{|}~";
foreach my $char ( split //, $chars ) {
printf( "\"" . $char . " some other text %d, %d\",\n", $a, $b );
# ...
}This should do the same, without substr or other cruft. |
|
#7
|
|||
|
|||
|
But $char_count is usually less than the number of chars in the string.
|
| Sponsored Links | ||
|
|
![]() |
| Tags |
| perl |
| Thread Tools | Search this Thread |
| Display Modes | |
|
|
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| PERL \c char in the string | Asteroid | Programming | 2 | 06-21-2010 02:29 AM |
| Parsing char string | ALTRUNVRSOFLN | Shell Programming and Scripting | 5 | 08-07-2008 06:25 PM |
| last char from a string | broli | Shell Programming and Scripting | 6 | 12-07-2007 07:02 PM |
| Extracting a string from one file and searching the same string in other files | mohancrr | Shell Programming and Scripting | 1 | 09-19-2007 03:17 AM |
| replacing char with string | phani_sree | Programming | 1 | 11-20-2006 07:57 AM |