The $ in the regex needs to be escaped (like this: s/ \$VAR1/ my %hash /) so Perl doesn't go looking for a variable named $VAR1 and complain when it can't find it.

Also, you have a subtle error in your code. The line if ($line = ~s/ \$VAR1/ my %hash /) is actually performing the search and replace on the default variable $_ (which hasn't been set to anything), taking the bitwise negation of the result (the number of replacements made, most likely zero) and assigning that result to the $line variable, which will most likely be true and execute the if block. The code should be like this:

... if ( $line =~ s/ \$VAR1/ my %hash / ) { ... } ...

In any case, this won't change your input file. You would need to write out to a new file after the search and replace.

A better way to do this is to specify the name of the variable when you dump your data structure using the $Data::Dumper::Varname variable, eg:

my %hash = (...); $Data::Dumper::Varname = 'hash'; print Dumper(\%hash);

An alternative is to use the object-oriented interface. You can specify your own names for your data structures, eg:

my %hash = (...); print Data::Dumper->Dump( [\%hash], ['hash'] );

See the docs for Data::Dumper for more details.

As an aside, you may want to consider dumping your data in a format such as XML or JSON, instead of as a Perl data structure.

Update: Minor clarifications re syntax.


In reply to Re: trouble with substitution by kejohm
in thread trouble with substitution by Interzona

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.