process($dir1, sub { s/blue/red/; s/yellow/green/; }); sub process { my $dir = shift; my $sub = shift; ... # pretty much like your own code, until we have to process the file contents: $sub->(); # note that the file contents is expected to be in $_ ... # rest of the wrapper code }