Path: utzoo!attcan!uunet!decwrl!ucbvax!iwarp.intel.com!news From: merlyn@iwarp.intel.com (Randal Schwartz) Newsgroups: comp.lang.perl Subject: Re: Changing the first character of a string. Message-ID: <1990Jun30.211102.14938@iwarp.intel.com> Date: 30 Jun 90 21:11:02 GMT References: Sender: news@iwarp.intel.com Reply-To: merlyn@iwarp.intel.com (Randal Schwartz) Organization: Stonehenge; netaccess via Intel, Beaverton, Oregon, USA Lines: 57 In-Reply-To: sean@ms.uky.edu (Sean Casey) In article , sean@ms (Sean Casey) writes: | | How can I change an arbitrary character of a string? I've got a fixed length | string, $flags, that is used in a printf. I need to be able to do something | like: | | $flags = " "; | | if ($mb_flags[$num] && $FL_UNREAD) { | set first character of $flags to 'U'; | } | if ($mb_flags[$num] && $FL_SENT) { | set second character of $flags to 'S'; | } | and so on substr() can be used as an lvalue. From the manpage: substr(EXPR,OFFSET,LEN) Extracts a substring out of EXPR and returns it. First character is at offset 0, or whatever you've set $[ to. If OFFSET is negative, starts that far from the end of the string. You can use the ================= substr() function as an lvalue, in which case EXPR ==================================================== must be an lvalue. If you assign something shorter =================== than LEN, the string will shrink, and if you assign something longer than LEN, the string will grow to accommodate it. To keep the string the same length you may need to pad or chop your value using sprintf(). In English (or something resembling English :-), this means that you can select portions of strings with substr, and then assign into them. So, a sample of what you wanted to do is: $flags = " " x 3; # hard to count spaces... :-) substr($flags,0,1) = "U"; print "<$flags>\n"; | That's why we need a perl book. I've written 40 or so odd perl scripts, and | something this simple evades me. I've written probably ten times that many *production* scripts (and many more one-ups), and I still find myself reading the manpage (and occasionally the code :-) from cover to cover to get what I need to know. I hope the book clears up some of the folklore and allows you to have access to our collective experience. for("hacker","Perl","another","Just"){substr($x,0,0)="$_ ";}substr($x,-1,1)=",";print$x -- /=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\ | on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III | | merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn | \=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/