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

Very Newbie Question. I am confused about using variables with <>. The following snippet works: unlink <*.old>; but this next snippet does not $Pattern = "*.old"; unlink <$Pattern>; Can someone please enlighten me? Thanks. Mike

Replies are listed 'Best First'.
Re: Using with a variable
by chromatic (Archbishop) on Apr 27, 2000 at 19:18 UTC
    I used this script for testing:
    #!/usr/bin/perl -w use strict; my $pattern = "*.old"; # unlink <$pattern>; unlink <*.old>;
    With use strict in place, uncommenting the first line reveals that Perl thinks $pattern holds a symbolic reference, at least in the way you've used it. That's what you meant it to do, but the interpreter doesn't do two levels of interpretation.

    The first level of interpretation is looking at what is in $pattern -- *.old in this case. It stops there, instead of interpreting THAT as a glob.

    The second example works because it can only be interpreted as a glob. You're just one level trickier than the Perl interpreter wants to be in this case.

Re: Using with a variable
by rmgiroux (Initiate) on Apr 27, 2000 at 21:15 UTC
    I believe that using <$var> makes perl try to read the filehandle named (contents of $var) if $var is a string, or the file $var points to if $var is a filehandle (i.e. $var=new IO::File("FileThingy");) .

    (Win32 examples; swap " and ' to use on Unix, and use ^D instead of ^Z)

    D:\>perl -e"$x='STDIN'; print <$x>;"
    abc
    def
    ^Z
    abc
    def
    d:\>copy con abc
    asd
    dsa
    zxc
    ^Z
    d:\>perl -MIO::File -e"$x=new IO::File('abc'); print <$x>"
    asd
    dsa
    zxc
    

    What you want is a glob; in this case, you're better off using the function notation for glob,

    unlink glob($Pattern);
    
    Hope this helps...
Re: Using with a variable
by merlyn (Sage) on Apr 28, 2000 at 06:27 UTC
Re: Using with a variable
by mcwee (Pilgrim) on Apr 27, 2000 at 20:05 UTC
    I'm fairly sure that
    <"$Pattern">
    will do what you want (I'd check, but am at work. Sorry.)

    The Autonomic Pilot

      Unfortunately, that didn't do it for me. I would guess that the <> operator has a higher precedence than the forced interpolation of the double quotes. On the plus side, specifying glob as rmgiroux points out works very well.

      (secret: put the print statement before the unlink and it will display how many files it unlinked.)