Subject: | Please make it object oriented. |
I can't subclass your module because it's not object oriented.
All that needs to be changed is this line added as first line to every
sub:
my $proto = @_ && UNIVERSAL::isa($_[0],__PACKAGE__) ? shift :
__PACKAGE__;
Then VolumeInfo can be called in object oriented context like this:
Win32::DriveInfo->VolumeInfo($drive)
...and can can be overridden like this:
Win32::DriveInfoNice->VolumeInfo($drive)
See attached example for sub class with VolumeInfo override.
If you call subs within the same class, then these must be called using
$proto->.
Subject: | t.pl |
#!/usr/bin/perl -w
use strict;
use Data::Dumper qw(Dumper);
# tab width = 4
{
package Win32::DriveInfoNice;
use Data::Dumper qw(Dumper);
use base qw(Win32::DriveInfo);
# Overrides parent method in order to returns a hash of information on success, else undef on error.
sub VolumeInfo {
my $proto = @_ && UNIVERSAL::isa($_[0],__PACKAGE__) ? shift : __PACKAGE__;
my $drive = shift;
# This doesn't work because parent class isn't designed to be used in object oriented context...
#my @info = $proto->SUPER::VolumeInfo($drive);
my @info = Win32::DriveInfo::VolumeInfo($drive);
# Return undef on error.
unless(@info >= 4) {
return undef;
}
# Coerce array result into a hashref.
my @names = qw(
VolumeName
VolumeSerialNumber
MaximumComponentLength
FileSystemName
);
my %result;
foreach my $name (@names) {
$result{$name} = shift(@info);
}
$result{'attr'} = \@info;
# Inject more useful information (again can't use $proto because of non-OO design of parent class).
my $type = $result{'DriveType'} = Win32::DriveInfo::DriveType($drive);
my %types = (
0 => 'unknown', # the drive type cannot be determined.
1 => 'unknown', # the root directory does not exist.
2 => 'removable', # the drive can be removed from the drive (removable).
3 => 'fixed', # the disk cannot be removed from the drive (fixed).
4 => 'network', # the drive is a remote (network) drive.
5 => 'optical', # the drive is a CD-ROM drive.
6 => 'ram', # the drive is a RAM disk.
);
$result{'DriveTypeName'} = $types{$type} || 'unknown';
return \%result;
}
}
package main;
my @drives = Win32::DriveInfo::DrivesInUse();
print 'Drives in use: ' . join(', ', @drives) . "\n";
foreach my $drive (@drives) {
print "Dump of VolumeInfo about drive $drive: ";
print Dumper(Win32::DriveInfoNice->VolumeInfo($drive));
print 'Drive type: ' . Win32::DriveInfo::DriveType($drive) . "\n";
print "\n";
}