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

I'd like to hold qr and strings in a file, then read them and put them into arrays, but the result is different then when I create the array statically in the code. How do I get $Var1 look like $VAR2?
CODE: use Data::Dumper; open(FILE, @ARGV[0]) || die "can't open output file"; @test = ('a', qr/b/, 'c', 'd'); while ( <FILE> ) { $hold[$i] = $_; chomp $hold[$i]; $i++; } print Dumper \@hold , \@test; OUTPUT: $VAR1 = [ 'a', 'qr/b/', 'c', 'd', 'e', '' ]; $VAR2 = [ 'a', qr/(?-xism:b)/, 'c', 'd' ];

Replies are listed 'Best First'.
Re: Reading from file
by gaal (Parson) on Jan 06, 2005 at 21:03 UTC
    You could translate qr// expressions as you read them.

    while (<FILE>) { chomp; s{^qr/(.*)/$}{qr/$1/}e; push @hold, $_; }

    Note that this data is tainted and potentially dangerous. Don't do this unless you trust your data.

Re: Reading from file
by osunderdog (Deacon) on Jan 06, 2005 at 21:01 UTC

    I believe that qr/b/ and qr/(?-xism:b)/ are equivalent.

    $perl -de 42 Reading ~/.perldb options. Loading DB routines from perl5db.pl version 1.25 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(-e:1): 42 DB<1> $v = qr/b/ DB<2> x $v 0 (?-xism:b) -> qr/(?-xism:b)/

    If you are trying to store off persistent data and read it back in later, you might look at Storable


    "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.

Re: Reading from file
by VSarkiss (Monsignor) on Jan 06, 2005 at 21:30 UTC
      Er, no. Strings do not generally evaluate to themselves.

      My suggestion would have evaled only purported regexps, which the author of the config file presumably does want to be interpolated. The other lines in the files don't match the pattern, and are not evaled.

      The warning was about (?{ }) expressions.

Re: Reading from file
by Thilosophy (Curate) on Jan 07, 2005 at 05:40 UTC
    The result is different because you set $test[1] = qr/b/ in your code, which is not the same as $test[1] = 'qr/b/'.

    qr/b/ creates a regular expression reference, which Dumper prints as qr/(?-xism:b)/, whereas 'qr/b/' is a plain string.

    If you want to read a regular expression reference from a file, you have to either write it with Storable (which results in a binary file you cannot edit by hand) or Data::Dump it (so that you can eval it back, with the obvious security implications) or do something like gaal is suggesting above.