Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

what is the use of derefernce in substitution?

by tej (Scribe)
on Sep 22, 2011 at 11:39 UTC ( [id://927329]=perlquestion: print w/replies, xml ) Need Help??

tej has asked for the wisdom of the Perl Monks concerning the following question:

What is the use of ${1} in the below statement instead of $1?

 $text =~ s/(<jrnl\;\d+\;)[^>]*(>)/${1}${annualIssue}\;${first}\\N${last}${2}/gs;

Thank you

Replies are listed 'Best First'.
Re: what is the use of derefernce in substitution?
by moritz (Cardinal) on Sep 22, 2011 at 11:48 UTC

    ${var} and $var are the same thing in an interpolation. People use the first form if the next thing after it is an identifier:

    say "${var}foo"; # interpolates $var, adds literal foo say "$varfoo"; # interpolates $varfoo

    So in your case there's no reason to write it, but it seems the author deemed the form with curlies safer.

Re: what is the use of derefernce in substitution?
by jwkrahn (Abbot) on Sep 22, 2011 at 11:45 UTC

    In that example there is no difference between ${1} or ${2} and $1 or $2.

    It could just as well be written as:

    $text =~ s/(<jrnl;\d+;)[^>]*(>)/$1$annualIssue;$first\\N$last$2/gs;
Re: what is the use of derefernce in substitution?
by Kc12349 (Monk) on Sep 22, 2011 at 18:12 UTC

    I, on occasion, do this in my code when adding a characters to an interpolated string, but generally there is a better way to do it. My preference is to concatenate variables individually instead of wrapping in double quotes.

    my $string1 = 'test'; my $string2 = "${string1}append"; # my preference my $string3 = $string1 . 'append';

    In the case of replacements this approach could be replicated with the /e modifier. Which again is just my preference, but is what I would do in this case.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-04-20 00:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found