A script that copies all files specified in a M3U playlist into a directory.

Requirements

Example

$ ./cpm3u.pl playlist.m3u /tmp/Music

Source code

cpm3u.pl

#!/usr/bin/perl -w
use strict;
use Cwd 'realpath';
use File::Basename;
use File::Copy;

if ( @ARGV != 2 ) { usage() }
my $src = $ARGV[0];
my $dest = $ARGV[1]; 
if ( ! -e $src ) { die("source m3u file does not exist") }
if ( ! -r $src ) { die("source m3u file can not be read") }
if ( ! -d $dest ) { die("destination is not a directory") }
if ( ! -w $dest ) { die("destination directory is not writable") }

# determine the absolute path of the directory the m3u file is in
my $m3udir = dirname( realpath( $src ) );
open( M3U, $src ) or die $!;

while ( <M3U> ) {
	chomp();
	my $file = $_;

# skip empty lines and comments
	if ( $file =~ /^$/ || $file =~ /^#/ ) { next() }

# if the line contains a relative path, prepend the absolute path of the
# directory the m3u file is in
	if ( $file !~ /^\// ) {
		$file = $m3udir . '/' . $file;
	}

	if ( -d $file ) {
		print( "$file is a directory. skipping...\n");
		next();
	}
	if ( ! -e $file ) {
		print( "$file does not exist. skipping...\n" );
		next();
	}

	print( "copying $file...\n" );
	copy( $file, $dest ) or warn $!;
}

# subroutine for printing usage information and ending the program
sub usage {
	my $errorString = shift;
	if ( defined( $errorString ) ) {
		print( "$errorString\n" );
	}
	print << "EOF";
$0 - copy all files specified in an m3u file to a directory

usage:	$0 m3u destination
EOF
	exit( 0 );
}