Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Forcing array context

by jarich (Curate)
on Nov 22, 2002 at 05:32 UTC ( [id://215009]=note: print w/replies, xml ) Need Help??


in reply to Forcing array context

I want to use a scalar $string in a very C-like way, that is I want to run through the @string character by character, fiddling with chars along the way.
Try something like
my @chars = split //, $string;
Then @chars has each character in it. So:
foreach my $char (split //, $some_string) { if($char eq " ") { print "it was a space!"; # change all spaces to |s $char = "|"; } }
or something like that. Then of course you join them together when you're done...
$string = join("", @chars);

Hope it helps.

jarich

Replies are listed 'Best First'.
Re: Re: Forcing array context
by jens (Pilgrim) on Nov 22, 2002 at 05:39 UTC
    A reasonable solution, but I want to do this without
    invoking the regex engine, so split is strictly taboo...Any other ideas?
    --
    Microsoft delendum est.
      If substr's okay, how about this kind of thing:
      my $string = "This is a very long string"; foreach (0..length($string)) { if(substr($string, $_, 1) eq " ") { # Replace this position (space) with a "|" substr($string, $_, 1, "|"); } } print $string;
      It kinda depends on what you're trying to do, but I think this might help. (Note that you can also replace with the empty string).

      Hope it does.

      jarich

      Update: forgot the length. ;)

      A reasonable solution, but I want to do this without invoking the regex engine
      When you say, "I wanna do $X", and the answer is "by doing $Y", and then you say "I wanna do $X but without doing $Y", you are obligated to provide a reason why the best/easiest way ($Y) is so easily dismissed. How close to doing $Y can you get, for example, and why not $Y? {grin}

      You haven't yet. Please do so.

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.

      What's the deal with imposing ridiculous, artificial restrictions? Split is the correct way to do it, so there.

      --
      Regards,
      Helgi Briem
      helgi AT decode DOT is

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://215009]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (9)
As of 2024-04-18 13:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found