How do you retrieve a char from a string?

Discussion in 'Perl Misc' started by Thierry, Jul 17, 2007.

  1. Thierry

    Thierry Guest

    I have the following string:

    my $greet = "hello";
    print $greet[0]."\n";

    The above clearly doesn't work since $greet is not an array. Is there
    an easy way to access characters at specific index in a string without
    losing $greet as a String?

    Thierry
    Thierry, Jul 17, 2007
    #1
    1. Advertising

  2. Thierry

    Mirco Wahab Guest

    Thierry wrote:
    > I have the following string:
    >
    > my $greet = "hello";
    > print $greet[0]."\n";
    >
    > The above clearly doesn't work since $greet is not an array. Is there
    > an easy way to access characters at specific index in a string without
    > losing $greet as a String?


    The canonical method is the one Sherm already mentioned,
    but(!):

    ...
    my $greet = 'hello';

    #0
    print substr($greet, 0, 1), "\n";

    #1
    print $greet =~ /.(.)/, "\n";

    #2
    print +(split //, $greet)[2], "\n";

    #3 (only 8bit chars)
    print chr( vec $greet, 3, 8 ), "\n";

    #4 (trounce and print last char)
    print chop $greet, "\n"

    Regards

    M.
    Mirco Wahab, Jul 17, 2007
    #2
    1. Advertising

  3. Thierry

    -berlin.de Guest

    Sherm Pendley <> wrote in comp.lang.perl.misc:
    > Thierry <> writes:
    >
    > > I have the following string:
    > >
    > > my $greet = "hello";
    > > print $greet[0]."\n";
    > >
    > > The above clearly doesn't work since $greet is not an array. Is there
    > > an easy way to access characters at specific index in a string without
    > > losing $greet as a String?

    >
    > print substr($greet, 0);


    That's the entire string. The first character is "substr($greet, 0, 1)".

    > See "perldoc -f substr" for details.


    I'll refrain fom commentig :)

    Anno
    -berlin.de, Jul 18, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. wwj
    Replies:
    7
    Views:
    538
  2. wwj
    Replies:
    24
    Views:
    2,478
    Mike Wahler
    Nov 7, 2003
  3. Ben Pfaff
    Replies:
    5
    Views:
    458
    Tristan Miller
    Jan 17, 2004
  4. Steffen Fiksdal

    void*, char*, unsigned char*, signed char*

    Steffen Fiksdal, May 8, 2005, in forum: C Programming
    Replies:
    1
    Views:
    569
    Jack Klein
    May 9, 2005
  5. lovecreatesbeauty
    Replies:
    1
    Views:
    1,009
    Ian Collins
    May 9, 2006
Loading...

Share This Page