Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Editing the contents of a variable

by ww (Bishop)
on Aug 21, 2012 at 11:33 UTC ( #988702=note: print w/ replies, xml ) Need Help??


in reply to Editing the contents of a variable

Better? Who knows? That depends on your intent, your data, etc.

More concise (and less reliance on $_... which is easy to overuse):

#!/usr/bin/perl use 5.014; # 988698 my $str = "yada yada <name> string-to-capture </name> foo bar baz"; if ( $str =~ m!<name>(.*?)<\/name>! ) { my $var1=$1; $var1 =~ s/ //g; # removing spaces? print "$var1\n"; }

However, if the actual "tags" are intended to be html, xml or suchlike, your "better way" almost certainly involves using an appropriate parser.


Comment on Re: Editing the contents of a variable
Download Code
Replies are listed 'Best First'.
Re^2: Editing the contents of a variable
by flexvault (Prior) on Aug 21, 2012 at 12:58 UTC

    ww,

    Just a thought, if the 'string-to-capture' had information separated by spaces, your code would eliminate all spaces, maybe the special case:

    my $str = "yada yada <name> string-to-capture string-to-capture2 </n +ame> foo bar baz"; if ( $str =~ m!<name>(.*?)<\/name>! ) { my $var1=$1; $var1 = join(" ", split " ", $var1 ); # remove leading, trailin +g and # collapse internal white +space print "$var1\n"; }
    would be better. ( Taken from Camel book 3rd edition, page 154 )

    "Well done is better than well said." - Benjamin Franklin

      The s/ //g is OP's. Comment (question) is mine as, (for most purposes I can imagine in the background of the OP,) it makes no obvious sense.

      Your reply, however, calls attention to that, which is a good thing, if OP is cargo-culting or had missed the implications. + +

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2015-07-31 10:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (276 votes), past polls