3

对于大学的作业,我们必须用 Perl 编写一个脚本,以便我们管理电子商店的库存。(给出的例子是亚马逊)。用户可以在完全基于文本的环境中下订单,并且在订单完成后必须更新库存。

库存中的每个项目都有 3 到 4 个属性:产品代码、标题、价格和某些数量(例如 MP3 没有此属性)

由于这是我第一次接触 Perl,我真的不知道如何开始。我的主要问题是我应该如何在程序中“实施”库存。该程序的功能之一是搜索标题。另一种是下订单,用户应提供产品代码。

我的第一个想法是以产品代码为键的散列。但是,如果我想搜索可能因此出现问题的标题:哈希键类似于 DVD-123,属于该键的信息可能是“The Green Mask 12”(不带引号),其中 12 表示目前有多少这张 DVD 有存货。所以我最终必须找到一种方法来忽略 12。

另一种解决方案是使用标题作为键,但我认为这也很麻烦。

有没有办法用 2 个键创建一个哈希表,当我只给出一个时,它会返回一个包含其他值的数组?(包括另一个密钥和其他信息)这样我就可以根据我需要的库存信息来使用另一个密钥。

我们必须从如下所示的文本文件中读取默认库存:

MP3-72|Lady Gaga - Kiss and Run (Fear of Commitment Monster)|0.99  
CD-400|莱昂之王-只在夜晚|14.50|2  
MP3-401|莱昂之王 - 近距离|0.85  
DVD-144|不死不活|14.99|2  
SOFT-864|Windows Vista|49.95  
4

4 回答 4

3

由于您的课程可能不涉及 SQL 或数据库,您可能会发现将您的库存表示为 hashes 的散列很有用。

库存项目将是哈希引用

my $die_hard_4 = { code => 'DVD-144', title => 'Live Free or Die Hard', price => 14.99, stock => 2 };

您的库存本身将是一个哈希:

my %inventory;
$inventory{'DVD-144'} = $die_hard_4;

您可以创建另一个散列来按标题索引您的库存:

my %inventory_by_title;
$inventory_by_title{'Live Free or Die Hard'} = $die_hard_4;

剩下的就是将库存文件格式解析为上面的 hashref。举个简单的例子:

my %inventory;
my %inventory_by_title;

while ( <> ) {   # for each line of input
    chomp;  # remove trailing newline
    my ($code, $title, $price, $amount) = split /\|/;  # split by '|' character
    my $item = {
        code => $code,
        title => $title,
        price => $price,
        stock => $amount,
    };
    $inventory{$code} = $item;
    $inventory_by_title{$title} = $item;
}

希望这可以帮助您入门。

于 2010-03-20T13:01:33.963 回答
1
#!/usr/bin/perl

use strict; use warnings;
use YAML;

my @store;

while ( my $inv = <DATA> ) {
    chomp $inv;
    last unless $inv =~ /\S/;

    my ($id, $title, $price, $stock) = split qr{\|}, $inv;
    $stock ||= 0;
    my ($type, $code) = split /-/, $id;
    push @store, {
        type  => $type,
        code  => $code,
        title => $title,
        price => $price,
        stock => $stock,
    };
}

print "DVDs\n";
print Dump [ grep { $_->{type} eq 'DVD'} @store ];

print "Products that cost less than \$15\n";
print Dump [ grep { $_->{price} < 15 } @store ];

print "Products that are in stock\n";
print Dump [ grep { $_->{stock} } @store ];

print "Products with 'of' in the title\n";
print Dump [ grep { $_->{title} =~ /of/ } @store ];

__DATA__
MP3-72|Lady Gaga - Kiss and Run (Fear of Commitment Monster)|0.99
CD-400|Kings of Leon - Only By The Night|14.50|2
MP3-401|Kings of Leon - Closer|0.85
DVD-144|Live Free or Die Hard|14.99|2
SOFT-864|Windows Vista|49.95
于 2010-03-20T13:47:15.540 回答
0

您可以使用sqlite、mysql 等数据库来存储库存数据而不是文本文件。然后,您可以使用 sql 命令从数据库中查询/更新/删除/选择并轻松操作您的库存数据

于 2010-03-20T12:43:49.657 回答
0

里面有很多问题。最简单的方法之一是如何制作包含列表的散列

没有带有两个键的散列,但散列很乐意指向“向左和向右”,例如:

$inventory{$title} = $product_code;
$inventory{$product_code} = $title;

当且仅当您可以确定您不会拥有名为“DVD123”的光盘。使用两个哈希值会更安全、更易读:

$inventory_by_title{$title} = ...
$inventory_by_code{$product_code} = ...
于 2010-03-20T12:56:35.080 回答