code:web
- #!/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;
- }
- }
結果:sql