http://qs321.pair.com?node_id=381146


in reply to using a subroutine

One thing you do which strict may call attention to is set a global variable in one subroutine and use it in another. It's better to just pass those values as arguments. You'll wind up with cleaner code that way.

You can also save yourself some trouble by realizing that unlink can take a list as argument, and that glob will produce a list of the kind you want. Here is a sub that illustrates a more economical approach.

my ($user, $lib) = qw(/home/john /lib); sub directs { my $count; for my $dir (@_) { $count += unlink map {glob "$dir/$_"} qw(*~ core.*); } $count; } print directs( $user, $lib), ' files deleted.', $/;
The map applies the code in its first argument to each element of the remaining arguments - here, globby versions of your regexen. The result is a list of matching filenames. unlink then acts on each, returning the number of files deleted in that pass.

Update: $/ is the input record seperator, by default your system's newline. You could say that as well with "\n". Using $/ is handy if you might want to change the line end, because then you can say, for instance,

{ local $/ = '<br />'; foo(@args); }
and the strings foo() prints will be terminated with html break tags. $\ could also be used (with even better justification) but it does not have the newline default value.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: using a subroutine
by xjlittle (Beadle) on Aug 10, 2004 at 00:50 UTC
    Zaxo,

    One other question after studying your code. On the last line:
    print directs( $user, $lib), ' files deleted.', $/;
    what does the $/; do?

    Thanks,

    John
Re^2: using a subroutine
by xjlittle (Beadle) on Aug 10, 2004 at 00:28 UTC
    This worked beautifully! Now all I need is to understand the map command better. I haven't seen that before. Thanks for the link and the advice!

    I do have a question though. When I first set this up I had a comma between (/home/john /lib) in the first line of code:
    my ($user, $lib) = qw(/home/john /lib);

    which caused it to not work. Why does the comma have this affect on this or any other script?

    John