Write a Perl script to calculate the lines of code of all C source and header files…
- User
Write a Perl script to calculate the lines of code of all C source and header files recursively within a directory
- Assistant
Here is a Perl script that recursively calculates the lines of code for all C source and header files within a given directory:
#!/usr/bin/perl use strict; use warnings; my $directory = '/path/to/directory'; # Specify the directory to search # Function to calculate lines of code sub count_lines_of_code { my $file = shift; my $line_count = 0; open(my $fh, '<', $file) or die "Cannot open file '$file' for reading: $!"; while (my $line = <$fh>) { # Skip empty and comment lines next if ($line =~ /^\s*$/ || $line =~ /^\s*\/\// || $line =~ /^\s*\/\*/); $line_count++; } close($fh); return $line_count; } # Function to search C files recursively sub search_files { my $dir = shift; opendir(my $dh, $dir) or die "Cannot open directory '$dir': $!"; my @files = readdir($dh); closedir($dh); foreach my $file (@files) { next if ($file =~ /^\./); # Skip hidden files and directories my $path = $dir . '/' . $file; if (-d $path) { search_files($path); # Recursively search subdirectories } else { if ($file =~ /\.(c|h)$/i) { # Match C source and header files my $line_count = count_lines_of_code($path); print "$path: $line_count lines\n"; } } } } search_files($directory);To use this script, replace
/path/to/directorywith the actual path of the directory you want to search. Save the script with a.plextension (e.g.,lines_of_code.pl) and execute it using Perl on the command line:perl lines_of_code.plThe script will recursively search through the specified directory and its subdirectories, and print the path of each C source and header file along with the corresponding lines of code count.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.