程序允许30分钟,期间要求用户输入来模拟车辆进入、出去的行为
输入的内容为一串字符串,每个不同的字符串代表一辆车.
纪录所有车每次进出的时间,计算时间、次数和价格.
价格依照价格表,阶梯定价:头10分钟5元,超过10分钟的每分钟5元
程序运行30分钟自动退出,程序退出前还没出库的车,收费200元
程序最后统计所有车辆的情况:次数,每次时间,总时间,总价
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Time::Local; use POSIX qw{strftime}; my (%hash,%count)=(); my $start_time = time; sub p_money{ #计算费用 my $time = shift; return 5 if $time <= 600; if ($time>600 and $time<1800){ my $min; $time%60==0?$min = ($time-600)/60:$min= int( ($time-600)/60 +1); my $mon_minute = 5+$min*5; return $mon_minute; } } my (@arr,$end_time); while(1){ my ($start); $end_time=time; print "Car Number :"; eval{ local $SIG{ALRM}=sub {die "timeout\n";}; alarm(5); chomp( $start = <>); #此处设施中断 5秒内没有用户输入就继续循环, push @{$hash{$start}},time; $count{$start}++ if defined $start; alarm(0); }; if ($end_time-$start_time>20){ #这里程序运行20秒,则退出循环,打印车辆的费用 for (sort keys %hash){ my $stop_time = time()-$hash{$_}[0]; my $car_start_time = strftime("%Y-%m-%d %H:%M:%S", localtime($hash{$_}[0])); my $car_stop_time = strftime("%Y-%m-%d %H:%M:%S", localtime(time)); push @arr,"$_\t$car_start_time $car_stop_time $stop_time\t200\n"; } print "\n车号\t开始时间\t离开时间\t停车时间\t价格\n"; print @arr; exit; } if(defined $start and ($count{$start}||0) >1 ){ push @{$hash{$start}},time; my $stop_time = $hash{$start}[-1]-$hash{$start}[0]; my $car_money = p_money $stop_time; my $car_start_time = strftime("%Y-%m-%d %H:%M:%S", localtime($hash{$start}[0])); my $car_stop_time = strftime("%Y-%m-%d %H:%M:%S", localtime($hash{$start}[-1])); push @arr, "$start\t$car_start_time $car_stop_time $stop_time\t$car_money\n"; delete $count{$start}; #删除 出库车辆 delete $hash{$start}; redo; #继续等待用户输入 }else{ redo; } }
时间: 2024-10-11 12:09:47