Hadi Nounou Hadi Nounou - 6 months ago 22
Perl Question

Can't access an mp3 file in perl

I am new to perl and was messing around with mp3 files using this program, but it doesn't seem to work.
So I want to access this file in my music folder and print it out, but whenever I'm running the script I'm getting the error:


Can't call method
get_tags
on an
undefined
value at line 5.


I know it's probably something basic but I couldn't find it on google. Thanks in advance

use 5.0.10;
#!/usr/bin/perl;
use MP3::Tag;
$mp3=MP3::Tag->new("C:\Users\plank223\Music\Ellie Goulding - Bright Lights (Deluxe Edition).mp3");
$mp3->get_tags();
if (exists $mp3->{ID3v1}) {
print "Filename: $filename\n";
print "Artist: " . $mp3->{ID3v1}->artist."\n";
print "Title: " . $mp3->{ID3v1}->title . "\n";
print "Album: " . $mp3->{ID3v1}->album . "\n";
print "Year: " . $mp3->{ID3v1}->year . "\n";
print "Genre: " . $mp3->{ID3v1}->genre . "\n";
} else {
print "Oi, no data here";
}
$mp3->close();

Answer

There are two things wrong with your program:

You are using double quotes " and backslashes in your Windows paths. Perl thinks you are trying to escape characters in the path with the backslash \. If you had read the complete error message, you would have seen something like this.

Unrecognized escape \m passed through at F:\scratch3.pl line 10. Unrecognized escape \D passed through at F:\scratch3.pl line 10. Unrecognized escape \D passed through at F:\scratch3.pl line 10. Unrecognized escape \D passed through at F:\scratch3.pl line 10.

That's Perl complaining about the escaped parts of the path. These error messages even show up without use strict. Always read the full error messages, not just the bottom one.

You can fix that by simply using single quotes ' instead of double quotes " for the path.

This is the reason why MP3::Tag->new fails. It will return undef, and you will subsequently call the get_tags method on an undefined value, as the last error message says.

After that, inside the loop, there is another mistake. You are using $filename, which you have not declared.

A working version of your program might look like this.

use MP3::Tag;
use strict;
use warnings;

# single quotes here!
my $filename = 
    'C:\Users\plank223\Music\Ellie Goulding - Bright Lights (Deluxe Edition).mp3'; 
my $mp3 = MP3::Tag->new($filename);
$mp3->get_tags;

if ( exists $mp3->{ID3v1} ) {
    print "Filename: $filename\n";
    print "Artist: " . $mp3->{ID3v1}->artist . "\n";
    print "Title: " . $mp3->{ID3v1}->title . "\n";
    print "Album: " . $mp3->{ID3v1}->album . "\n";
    print "Year: " . $mp3->{ID3v1}->year . "\n";
    print "Genre: " . $mp3->{ID3v1}->genre . "\n";
}
else {
    print "Oi, no data here";
}
$mp3->close;
Comments