如何调整现有Perl脚本以满足系统更新升级及指定包安装需求?
Revised Perl Script & Explanation
Great question! Let's get your Perl script squared away to meet all your requirements. Here's the polished, working version first:
#!/usr/bin/perl use strict; use warnings; # Define one or more packages to install (separate with spaces for multiple) my $packages = "nginx git curl"; sub Install { # Update system package repositories print "Updating package lists...\n"; system("sudo apt update") == 0 or die "Failed to update repositories: $!"; # Upgrade all installed packages print "Upgrading existing packages...\n"; system("sudo apt upgrade -y") == 0 or die "Failed to upgrade packages: $!"; # Install the pre-defined packages print "Installing specified packages: $packages...\n"; system("sudo apt install -y $packages") == 0 or die "Failed to install packages: $!"; print "✅ All operations completed successfully!\n"; } # Execute the installation routine Install();
Key Changes & Why I Made Them:
- Enabled strict mode and warnings: Always start Perl scripts with
use strict;anduse warnings;— these tools catch typos, undefined variables, and other subtle bugs before they cause problems. They're non-negotiable for reliable Perl code. - Improved the package variable: Renamed the vague
$xto$packagesfor readability, and formatted it to support multiple packages (just separate names with spaces, like the example above). - Fixed APT command syntax: Your original commands had incorrect hyphenation — it's
apt update,apt upgrade, andapt install(no hyphens betweenaptand the command). I also added the-yflag to each command to auto-confirm prompts, so the script runs fully unattended without waiting for user input. - Fixed case sensitivity: Perl is case-sensitive! You defined
sub Installbut tried to callinstall()— this would throw an error. I corrected the call toInstall()to match the subroutine name. - Added error handling: Each
system()call now checks if it exited successfully. If any step fails, the script dies with a clear error message, so you know exactly where things went wrong instead of guessing. - Added progress feedback: Simple print statements let you track the script's progress, so you aren't left wondering if it's stuck or working.
内容的提问来源于stack exchange,提问作者Kimberly Harris
相关产品推荐
相关产品推荐

