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

Hello again, good monks.This is my case:
foreach (readline FILE1) { if (/$hashnew{$com}/){ print WFILE "$_\n"; } }
$hashnew{$com} has value - the word "context". How do I make the script to treat $hashnew{$com} as it's value,i.e. in this case to treat it as context. Thanks a lot in advance.

Edited by Chady -- code tags, fixed spaces in the code part.

Replies are listed 'Best First'.
Re: File parsing
by dave_the_m (Monsignor) on Jun 30, 2004 at 11:31 UTC
    As an aside, you might want to replace
    foreach (readline FILE) {
    with
    while (<FILE>) {
    The former reads the whole file into memory before processing it, which may become a problem with large files.

    Dave.

Re: File parsing
by tachyon (Chancellor) on Jun 30, 2004 at 11:29 UTC

    As borisz says it should work. Add a sanity check to ensure it really contains what you expect like this (note the quotes around the value let you see hidden spaces/newlines which may be the issue)

    warn "Value of \$hashnew{\$com}: '$hashnew{$com}'\n"; while(<FILE1>) { print WFILE $_ if m/$hashnew{$com}/; }

    A while loop is a more usual way to iterate over a files content and more efficient that your foreach. Newlines remain attached so you don't need to add one when you print the file out (unless you are using -l switch)

    On unix you could get the same functionality of this snippet with something like grep context file1 > wfile

    cheers

    tachyon

Re: File parsing
by borisz (Canon) on Jun 30, 2004 at 11:20 UTC
    do nothing, it works already that way.
    Boris
Re: File parsing
by calin (Deacon) on Jun 30, 2004 at 14:17 UTC

    In addition:

    If you want to treat the value of $hashnew{$com} as a string literal (avoid regexp semantics), use the \Q...\E construct:

    if (/\Q$hashnew{$com}\E/) { # ...

    This is highly recommended if $hashnew{$com} comes from untrusted sources (because otherwise it can open a security hole). It also helps avoid weird behaviour or sudden death (in case $hashnew{$com} happens to contains regexp control characters).

    If you want to avoid the regexp overhead, you can use index:

    if (index($_, $hashnew{$com}) + 1) { # ...

    All of the above applies only if you want $hashnew{$com} to behave as a simple substring, not as a sub-regexp. (your post is vague, so I'm guessing)