gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
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);