package Text::Playlist::PLS; use strict; use warnings; use base 'Text::Playlist'; our $VERSION = 0.1; sub new { my ($class) = @_; return bless({ items => [] }, $class); } sub add { my ($self, %args) = @_; foreach my $key (qw(file title)) { next if $args{$key}; return "Missing '$key' parameter"; } $self->{items} //= []; push @{$self->{items}}, { file => $args{file}, title => $args{title}, length => $args{length} || "-1", }; return; } sub parse { my ($self, $text) = @_; my @lines = split /\r?\n/, $text; my @items = (); # safeguard return "Not looks like playlist" unless grep { $_ eq "[playlist]" } @lines; my $count = 0; foreach my $line (@lines) { if ($line =~ m/(File|Title|Length)(\d+)\s*=\s*(.*)/oi) { my ($key, $num, $value) = (lc($1), $2 - 1, $3); $value =~ s/(^\s*|\s*$)//og; $items[$num] //= {}; $items[$num]->{$key} = $value; next; } if ($line =~ m/numberofentries\s*=\s*(\d+)/oi) { $count = $1; next; } } warn "Number of entries not matches parsed items" if ($count != scalar @items); return wantarray ? @items : [ @items ]; } sub dump { my ($self, @items) = @_; my $count = 0; my @lines = ('[playlist]'); foreach my $item (@items) { $count += 1; foreach my $key (qw(file title length)) { push @lines, sprintf("%s%d=%s", ucfirst($key), $count, $item->{$key}); } } splice(@lines, 1, 0, sprintf("numberofentries=%d", $count)); push @lines, "Version=2", ""; return join("\n", @lines); } 1;