Perl XML Parser

I had started downloading videos from UC Berkeley . I got an rss file but the problem was I got very big names like : 3ad1c4e4-5e5d-49a8-baf6-c2497fd6d091_opencast_video_itunes-wcb.mp4 .
So I wrote a perl script to read the rss file and rename the files. 


#!/usr/bin/perl -s

use strict;
use warnings;
use XML::Simple;

#print "Loading the XML file ... \n";
our $file = shift;
my $doc = XMLin($file);

#foreach (keys %{$doc}) {
#       print "$_, ${$doc}{$_}\n";
#}

#print "----------\n Channel\n----------\n";
my %channel = %{${$doc}{channel}};
#foreach (sort keys %channel) {
#       print "$_, $channel{$_}\n";
#}

#print "----------\n Items\n----------\n";
my @item = @{$channel{item}};
my %names;
my $count = 1;

#print "Generating filenames ... \n";
foreach (@item) {
#       print "$_\n";
my %info_hash = %{$_};
my ($filename, $filetitle);

#       print "----------\n Info Hash\n----------\n";
foreach (sort keys %info_hash) {
if (/guid/) {
$filename = ${$info_hash{$_}}{content};
#                       print "FN: ", $filename, " -> ";
} elsif (/\btitle/) {
$filetitle = $info_hash{$_};
#                       print "FT:", $filetitle, "\n";
$filetitle =~ s/\s/_/g;
# Prefixing the filenames with ordered / unique numbers
$filetitle = "L" . sprintf("%03d", $count) . "-" . $filetitle
# Appending the extension
. substr($filename, index("$filename", '.'));
$names{$filetitle} = $filename;
$count++;
}
}
}

# ------------- For Testing ------------------ #
# This just creates dummy files with the actual filenames
# and writes the filename into the same file.
#foreach (values %names) {
#       print "Creating file $_\n";
#       open LECT, ">$_";
#       print LECT "$_" ;
#       close LECT;
#}
# ------------- For Testing ------------------ #

# print "Renaming files ... \n";
foreach (sort keys %names) {
print "Renaming file $names{$_} to $_\n";
rename($names{$_}, $_);
}

Comments

Popular Posts